A regular expression is an expression method for extracting and replacing a part of a character string and checking whether the character string satisfies the constraint.
Scene with regular expressions
In the case of the field to enter the telephone number on the registration form. Some people type with a hyphen, while others type without a hyphen. In order to unify the format, if there is a hyphen in the entered phone number, it will be processed as necessary.
Input field:090-1234-5678
⇓ Remove hyphens
09012345678
In this way, the technique for checking whether a specific character is included in a character string and performing operations such as removing a specific character is called ** regular expression **.
◾ sub method ◾ match method
** ◾ sub **
** (Example) ** Replaced the string "eat bread" with the string "eat rice".
irb(main):001:0> str = "Eat bread"
=> "Eat bread"
irb(main):002:0> str.sub(/Bread/,"rice")
=> "eat rice"
** ◾ match ** <Extraction / constraint survey> The match method is a method to check whether the character string specified in the argument is included in the character string using the method. If it is included, the specified string will be returned as an object called MatchData. If it is not included, the return value is nil.
** (Example) ** Check if the character string "Good morning" contains the character string "Good"
irb(main):001:0> str = "Good morning"
=> "Good morning"
irb(main):002:0> str.match(/Good/)
=> #<MatchData "Good">
irb(main):003:0> str.match(/Hello/)
=> nil
MatchData The matched string is returned as an object of type MatchData. If you want to extract the character string that actually matches from MatchData, you can extract it in the same way as when extracting the first data from the array.
irb(main):001:0> str = "good morning"
=> "good morning"
irb(main):002:0> md = str.match(/good/)
=> #<MatchData "good">
irb(main):003:0> md[0]
=> "good"
Recommended Posts