Common quick usage
suggest changeRegular expressions are often used in methods as parameters to check if other strings are present or to search and/or replace strings.
You’ll often see the following:
string = "My not so long string"
string[/so/] # gives so
string[/present/] # gives nil
string[/present/].nil? # gives true
You can use that match as a check for whether a string contains a substring:
puts "found" if string[/so/]
You can also ask for one capture group. The second argument is the group number. Numbering starts at 1, not 0 (0 would be the whole match). A group is the text enclosed in parentheses.
string[/(n.t).+(l.ng)/, 2] # gives long
Also often used: search and replace with sub or gsub, \1 gives the first found group, \2 the second:
string.gsub(/(n.t).+(l.ng)/, '\1 very \2') # My not very long string
The last match is remembered in the globals $1, $2, and so on, for the rest of the current scope:
$2 # gives long
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents