End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
MatchData#[]
mtch[i] → str or nil
mtch[start, length] → array
mtch[range] → array
mtch[name] → str or nil
re.c
View on GitHub ↗
static VALUE
match_aref(int argc, VALUE *argv, VALUE match)
{
VALUE idx, length;
match_check(match);
rb_scan_args(argc, argv, "11", &idx, &length);
if (NIL_P(length)) {
if (FIXNUM_P(idx)) {
return rb_reg_nth_match(FIX2INT(idx), match);
}
else {
int num = namev_to_backref_number(RMATCH_REGS(match), RMATCH(match)->regexp, idx);
if (num >= 0) {
return rb_reg_nth_match(num, match);
}
else {
return match_ary_aref(match, idx, Qnil);
}
}
}
else {
long beg = NUM2LONG(idx);
long len = NUM2LONG(length);
long num_regs = RMATCH_REGS(match)->num_regs;
if (len < 0) {
return Qnil;
}
if (beg < 0) {
beg += num_regs;
if (beg < 0) return Qnil;
}
else if (beg > num_regs) {
return Qnil;
}
if (beg+len > num_regs) {
len = num_regs - beg;
}
return match_ary_subseq(match, beg, len, Qnil);
}
}
Match Reference – MatchData acts as an array, and may be accessed using the normal array indexing techniques. mtch[0] is equivalent to the special variable $&, and returns the entire matched string. mtch[1], mtch[2], and so on return the values of the matched backreferences (portions of the pattern between parentheses).
Example
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m #=> #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8"> m[0] #=> "HX1138" m[1, 2] #=> ["H", "X"] m[1..3] #=> ["H", "X", "113"] m[-3, 2] #=> ["X", "113"] m = /(?<foo>a+)b/.match("ccaaab") m #=> #<MatchData "aaab" foo:"aaa"> m["foo"] #=> "aaa" m[:foo] #=> "aaa"