Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →
instance method · added in Ruby 3.2
MatchData#byteoffset
(::MatchData::capture backref) -> ([ ::Integer, ::Integer ] | [ nil, nil ])
mtch.byteoffset(n) → array
re.c
View on GitHub ↗
static VALUE
match_byteoffset(VALUE match, VALUE n)
{
int i = match_backref_number(match, n);
match_check(match);
backref_number_check(match, i);
if (RMATCH_BEG(match, i) < 0)
return rb_assoc_new(Qnil, Qnil);
return rb_assoc_new(LEN2NUM(RMATCH_BEG(match, i)), LEN2NUM(RMATCH_END(match, i)));
}
Returns a two-element array containing the beginning and ending byte-based offsets of the nth match. n can be a string or symbol to reference a named capture.
Example
m = /(.)(.)(\d+)(\d)/.match("THX1138.") m.byteoffset(0) #=> [1, 7] m.byteoffset(4) #=> [6, 7] m = /(?<foo>.)(.)(?<bar>.)/.match("hoge") p m.byteoffset(:foo) #=> [0, 1] p m.byteoffset(:bar) #=> [2, 3]
Ruby version changes
-
3.2
-
MatchData#byteoffsethas been added. [Feature #13110]
-