About Ruby regular expressions (metacharacters, captures, related methods)


Now that I've started to learn regular expressions, I'll write about how to use them as a reminder.

Sample code

Suppose you have a profile like this:

text = <<TEXT
Birthday:Born May 6, 1234
Postal code:789-1111

If you want to extract only numbers from your date of birth

#=> 1234,5,6 is extracted.
#=>Below, the kanji for the date will also match.
#=>May 6, 1234

Regular expression metacharacter meaning

** \ 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

If you want to remove the hyphen "-" between the zip codes

p text[/\d{3}-\d{4}/].gsub('-','')

Meaning of regular expression metacharacters and methods

** / (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.

A tool for testing regular expressions

Regular expressions can be visually confirmed using tools that can be tried and errored because they make full use of metacharacters. reg_exp.png


At the end

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

About Ruby regular expressions (metacharacters, captures, related methods)
About regular expressions in Ruby
About Ruby methods
About Ruby instance methods
About regular expressions used in ruby sub method
Regular expressions
About Ruby symbols
About ruby ​​form
About Ruby Hashes
About singular methods
About HttpServlet () methods
About Ruby arrays
About Ruby inheritance
About ruby block
About Ruby Hashes
Ruby Learning # 15 Methods
About Ruby Symbols
About Ruby variables
Ruby regular expression