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
2 changes: 2 additions & 0 deletions mrbgems/mruby-regexp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ re.match(:symbol) # a Symbol is matched against its name
re.source # => "pattern"
re.options # => flags integer
re.named_captures # => {"name" => [group_number], ...}
re.names # => ["name", ...]
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Regexp.escape("a.b") # => "a\\.b"
Regexp.last_match(n) # => nth capture from last match

Expand All @@ -71,6 +72,7 @@ md.end(0) # => match end position
md.pre_match # => string before match
md.post_match # => string after match
md.named_captures # => {"name" => "value", ...}
md.names # => ["name", ...]

# String methods
str.match(re) # => MatchData or nil
Expand Down
10 changes: 10 additions & 0 deletions mrbgems/mruby-regexp/mrblib/regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@ def named_captures
result
end

# Return the capture names in group order
def names
table = @named_captures
table ? table.keys : []
end

# options is implemented in C (internal flags -> Ruby constants conversion)

def self.last_match(n = nil)
Expand All @@ -27,4 +33,8 @@ def self.last_match(n = nil)

class MatchData
# named_captures is implemented in C via md->regexp

def names
regexp.names
end
end
14 changes: 14 additions & 0 deletions mrbgems/mruby-regexp/test/regexp.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1214,6 +1214,15 @@ def -(other)
assert_equal({"a" => [1]}, re.named_captures)
end

assert("Regexp#names") do
assert_equal ["year", "month", "day"],
/(?<year>\d+)-(?<month>\d+)-(?<day>\d+)/.names
assert_equal [], /\d+/.names

# a name that is registered twice is reported once, as in CRuby
assert_equal ["tag"], /(?<tag>\w+)-(?<tag>\w+)/.names
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 Expand Up @@ -1287,6 +1296,11 @@ def -(other)
assert_equal "host", nc["b"]
end

assert("MatchData#names") do
assert_equal ["a", "b"], /(?<a>\w+)@(?<b>\w+)/.match("user@host").names
assert_equal [], /\w+/.match("user").names
end

assert("Regexp - named captures survive /x preprocessing") do
# Regression: with /x, mrb_re_compile freed the stripped buffer that
# named_captures[i].name pointed into.
Expand Down
Loading