Regexp

The regular expression class. See Regular Expression Literals for more information.

Superclass

Class Methods

Regexp.last_match

Returns the MatchData object for the last regular expression match performed in the current scope. This method call is identical to a $~ reference.

/(.)(.)/ =~ "ab"
p Regexp.last_match      # => #<MatchData:0x4599e58>
p Regexp.last_match[0]   # => "ab"
p Regexp.last_match[1]   # => "a"
p Regexp.last_match[2]   # => "b"
p Regexp.last_match[3]   # => nil
Regexp.last_match([nth])

If the integer nth is 0, returns the matching string ($&). Otherwise, returns the substring matching the nth set of parentheses ($1, $2, ...). When there are no corresponding parentheses or no matches, returns nil.

/(.)(.)/ =~ "ab"
p Regexp.last_match      # => #<MatchData:0x4599e58>
p Regexp.last_match(0)   # => "ab"
p Regexp.last_match(1)   # => "a"
p Regexp.last_match(2)   # => "b"
p Regexp.last_match(3)   # => nil

Because Regexp.last_match, with no arguments, returns nil when the entire regular expression does not match, the format last_match[1] will throw a NameError exception. On the other hand, last_match(1) returns nil.

Methods

self =~ string
self === string

Matches the string string to a regular expression. If the argument is not a string or does not match, returns false; if it matches, returns true.

Matching information can be set in the built-in variable $~.

If string is neither nil nor a String object, throws a TypeError exception.

match(str)

Identical to self=~str, except that it does not return a MatchData object. If there is no match, returns nil.

When only the substring matching the regular expression is needed, use match(str) like this:

bar = /foo(.*)baz/.match("foobarbaz").to_a[1]

_, foo, bar, baz = */(foo)(bar)(baz)/.match("foobarbaz")

to_a takes failed matches into account.

to_s

Creates and returns a string expression for a regular expression. Preserves the meaning of the returned string even if the string is embedded in another regular expression.

re = /foo|bar|baz/i
p re.to_s       # => "(?i-mx:foo|bar|baz)"
p /#{re}+/o     # => /(?i-mx:foo|bar|baz)+/

However, some regular expressions with backreferences may not work as expected. This is because backreferences can only be specified by number at present.

re = /(foo|bar)\1/      # # \1 is foo or bar
p /(baz)#{re}/          # \1 is baz

# => /(baz)(?-mix:(foo|bar)\1)/