End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method · added in Ruby 3.1
MatchData#match_length
match_length(n) → integer or nil
match_length(name) → integer or nil
re.c
View on GitHub ↗
static VALUE
match_nth_length(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
struct re_registers *regs = RMATCH_REGS(match);
match_check(match);
backref_number_check(regs, i);
if (BEG(i) < 0)
return Qnil;
update_char_offset(match);
const struct rmatch_offset *const ofs =
&RMATCH(match)->rmatch->char_offset[i];
return LONG2NUM(ofs->end - ofs->beg);
}
Returns the length (in characters) of the matched substring corresponding to the given argument.
When non-negative argument n is given, returns the length of 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_length(0) # => 6 m.match_length(4) # => 1 m.match_length(5) # => nil
When string or symbol argument name is given, returns the length of the matched substring for the named match:
Example
m = /(?<foo>.)(.)(?<bar>.+)/.match("hoge") # => #<MatchData "hoge" foo:"h" bar:"ge"> m.match_length('foo') # => 1 m.match_length(:bar) # => 2
Ruby version changes
-
3.1
-
MatchData#match_lengthis added [Feature #18172]
-