Method: Regexp.last_match
- Defined in:
- re.c
.last_match ⇒ MatchData? .last_match(n) ⇒ String? .last_match(name) ⇒ String?
With no argument, returns the value of $~
, which is the result of the most recent pattern match (see Regexp global variables):
/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:
/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:
Regexp.last_match(-1) # => "a"
With string or symbol argument name
, returns the string value for the named capture, if any:
/(?<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.
4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 |
# File 're.c', line 4642 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(); } |