Now that I've started to learn regular expressions, I'll write about how to use them as a reminder.
Suppose you have a profile like this:
text = <<TEXT
Birthday:Born May 6, 1234
Postal code:789-1111
TEXT
(\d+)Year(\d+)Month(\d+)Day
#=> 1234,5,6 is extracted.
#=>Below, the kanji for the date will also match.
\d+Year\d+Month\d+Day
#=>May 6, 1234
** \ d ** ・ ・ ・ Half-width numbers (regardless of digits) ** + ** ・ ・ ・ The previous character or pattern is continuous at least once ** () ** ・ ・ ・ Capture or group the internally matched character strings ** Year, month, day ** ・ ・ ・ Not a metacharacter, just a character string
p text[/\d{3}-\d{4}/].gsub('-','')
#=>7891111
** / (Regular expression) / ** ・ ・ ・ Create a regular expression object by enclosing it in / (called "regular expression literal in Ruby") ** [] ** ・ ・ ・ String class method that extracts the part that matches the regular expression from the character string. The alias method is the ** slice ** method. ** {3}, {4} ** ・ ・ ・ The previous character (\ d in this case) continues for the number enclosed in {}. - ・ ・ ・ Not a metacharacter, just a hyphen. (Note that hyphens may represent "character range" depending on how they are written.) ** gsub ('1st argument','2nd argument') ** ・ ・ ・ Replace the character string that matches the 1st argument with the character string of the 2nd argument. In the above case, the character string "-" is converted to "" (meaning deletion). The ** slice ** method and ** gsub ** method each have a "destructive method ()". () A method that changes the state of the called object. Add "!" At the end.
Regular expressions can be visually confirmed using tools that can be tried and errored because they make full use of metacharacters.
https://rubular.com/
A regular expression that works well when searching and replacing strings. I wanted to master it in the near future, so I first described the basic learning content. Thank you for reading this far.
Recommended Posts