End of Life Ruby 3.0 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
instance method
MatchData#named_captures
mtch.named_captures → hash
re.c
View on GitHub ↗
static VALUE
match_named_captures(VALUE match)
{
VALUE hash;
struct MEMO *memo;
match_check(match);
if (NIL_P(RMATCH(match)->regexp))
return rb_hash_new();
hash = rb_hash_new();
memo = MEMO_NEW(hash, match, 0);
onig_foreach_name(RREGEXP(RMATCH(match)->regexp)->ptr, match_named_captures_iter, (void*)memo);
return hash;
}
Returns a Hash using named capture.
A key of the hash is a name of the named captures. A value of the hash is a string of last successful capture of corresponding group.
Example
m = /(?<a>.)(?<b>.)/.match("01") m.named_captures #=> {"a" => "0", "b" => "1"} m = /(?<a>.)(?<b>.)?/.match("0") m.named_captures #=> {"a" => "0", "b" => nil} m = /(?<a>.)(?<a>.)/.match("01") m.named_captures #=> {"a" => "1"} m = /(?<a>x)|(?<a>y)/.match("x") m.named_captures #=> {"a" => "x"}