Skip to content

Commit efe1ca5

Browse files
committed
define keys on RegexMatch
1 parent d5a8367 commit efe1ca5

File tree

2 files changed

+12
-6
lines changed

2 files changed

+12
-6
lines changed

base/regex.jl

+11-6
Original file line numberDiff line numberDiff line change
@@ -139,16 +139,21 @@ struct RegexMatch
139139
regex::Regex
140140
end
141141

142+
function keys(m::RegexMatch)
143+
idx_to_capture_name = PCRE.capture_names(m.regex.regex)
144+
return ntuple(length(m.captures)) do i
145+
# If the capture group is named, return it's name, else return it's index
146+
get(idx_to_capture_name, i, i)
147+
end
148+
end
149+
142150
function show(io::IO, m::RegexMatch)
143151
print(io, "RegexMatch(")
144152
show(io, m.match)
145-
idx_to_capture_name = PCRE.capture_names(m.regex.regex)
146-
if !isempty(m.captures)
153+
capture_keys = keys(m)
154+
if !isempty(capture_keys)
147155
print(io, ", ")
148-
for i = 1:length(m.captures)
149-
# If the capture group is named, show the name.
150-
# Otherwise show its index.
151-
capture_name = get(idx_to_capture_name, i, i)
156+
for (i, capture_name) in enumerate(capture_keys)
152157
print(io, capture_name, "=")
153158
show(io, m.captures[i])
154159
if i < length(m.captures)

test/regex.jl

+1
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
@test !haskey(m, "foo")
8282
@test (m[:a], m[2], m["b"]) == ("x", "y", "z")
8383
@test sprint(show, m) == "RegexMatch(\"xyz\", a=\"x\", 2=\"y\", b=\"z\")"
84+
@test keys(m) = (:a, 2, :b)
8485
end
8586

8687
# Backcapture reference in substitution string

0 commit comments

Comments
 (0)