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
re.c
View on GitHub ↗
static VALUE
rb_reg_s_last_match(int argc, VALUE *argv, VALUE _)
{
if (rb_check_arity(argc, 0, 1) == 1) {
VALUE match = rb_backref_get();
int n;
if (NIL_P(match)) return Qnil;
n = match_backref_number(match, argv[0]);
return rb_reg_nth_match(n, match);
}
return match_getter();
}
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.