Skip to content
class method

Regexp.last_match

() -> ::MatchData?
(::MatchData::capture capture) -> ::String?
Regexp.last_match → matchdata or nil
Regexp.last_match(n) → string or nil
Regexp.last_match(name) → string or nil

With no argument, returns the value of $~, which is the result of the most recent pattern match (see Regexp global variables):

Example
/c(.)t/ =~ 'cat'  # => 0
Regexp.last_match # => #<MatchData "cat" 1:"a">
/a/ =~ 'foo'      # => nil
Regexp.last_match # => nil

With non-negative integer argument n, returns the _n_th field in the matchdata, if any, or nil if none:

Example
/c(.)t/ =~ 'cat'     # => 0
Regexp.last_match(0) # => "cat"
Regexp.last_match(1) # => "a"
Regexp.last_match(2) # => nil

With negative integer argument n, counts backwards from the last field:

Example
Regexp.last_match(-1)       # => "a"

With string or symbol argument name, returns the string value for the named capture, if any:

Example
/(?<lhs>\w+)\s*=\s*(?<rhs>\w+)/ =~ 'var = val'
Regexp.last_match        # => #<MatchData "var = val" lhs:"var"rhs:"val">
Regexp.last_match(:lhs)  # => "var"
Regexp.last_match('rhs') # => "val"
Regexp.last_match('foo') # Raises IndexError.
See also .json_create .linear_time? .escape .new also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0