Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →
instance method · added in Ruby 3.1
MatchData#match
(::MatchData::capture backref) -> ::String?
match(n) → string or nil
match(name) → string or nil
re.c
View on GitHub ↗
static VALUE
match_nth(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
struct re_registers *regs = RMATCH_REGS(match);
backref_number_check(regs, i);
long start = BEG(i), end = END(i);
if (start < 0)
return Qnil;
return rb_str_subseq(RMATCH(match)->str, start, end - start);
}
Returns the matched substring corresponding to the given argument.
When non-negative argument n is given, returns the matched substring for the nth match:
Example
m = /(.)(.)(\d+)(\d)(\w)?/.match("THX1138.") # => #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8" 5:nil> m.match(0) # => "HX1138" m.match(4) # => "8" m.match(5) # => nil
When string or symbol argument name is given, returns the matched substring for the given name:
Example
m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge") # => #<MatchData "hoge" foo:"h" bar:"ge"> m.match('foo') # => "h" m.match(:bar) # => "ge"
Ruby version changes
-
3.1
-
MatchData#matchis added [Feature #18172]
-