Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions mrbgems/mruby-regexp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ re === "string" # => true/false (for case/when)
re.match(:symbol) # a Symbol is matched against its name
re.source # => "pattern"
re.options # => flags integer
re.named_captures # => {"name" => [group_number], ...}
Regexp.escape("a.b") # => "a\\.b"
Regexp.last_match(n) # => nth capture from last match

Expand Down
10 changes: 8 additions & 2 deletions mrbgems/mruby-regexp/mrblib/regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,15 @@ def self.compile(pattern, *args)
new(pattern, *args)
end

# Return named captures hash: {"name" => group_number, ...}
# Return named captures hash: {"name" => [group_number, ...], ...}
# @named_captures holds the internal name -> group_number table, so a fresh
# Hash is derived on every call and the caller cannot corrupt the table.
def named_captures
@named_captures || {}
table = @named_captures
return {} unless table
result = {}
table.each { |name, group| result[name] = [group] }
result
end

# options is implemented in C (internal flags -> Ruby constants conversion)
Expand Down
11 changes: 11 additions & 0 deletions mrbgems/mruby-regexp/test/regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1197,6 +1197,17 @@ def -(other)
assert_equal "2026", md["year"]
end

assert("Regexp#named_captures") do
assert_equal({"year" => [1], "month" => [2], "day" => [3]},
/(?<year>\d+)-(?<month>\d+)-(?<day>\d+)/.named_captures)
assert_equal({}, /\d+/.named_captures)

# the returned Hash is a copy; mutating it must not affect a later call
re = /(?<a>x)/
re.named_captures["a"] = 99
assert_equal({"a" => [1]}, re.named_captures)
end

assert("Regexp - empty group name") do
# (?<>x) used to compile and answer to "", and in /x mode the stored name
# pointed into the preprocessing buffer the compiler frees on the way out.
Expand Down
Loading