Skip to content

Commit 380abc8

Browse files
authored
define keys on RegexMatch (#37299)
1 parent 2b13234 commit 380abc8

File tree

3 files changed

+13
-6
lines changed

3 files changed

+13
-6
lines changed

NEWS.md

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ Standard library changes
4646
* `escape_string` can now receive a collection of characters in the keyword
4747
`keep` that are to be kept as they are. ([#38597]).
4848
* `getindex` can now be used on `NamedTuple`s with multiple values ([#38878])
49+
* `keys(::RegexMatch)` is now defined to return the capture's keys, by name if named, or by index if not ([#37299]).
4950

5051
#### Package Manager
5152

base/regex.jl

+11-6
Original file line numberDiff line numberDiff line change
@@ -149,16 +149,21 @@ struct RegexMatch <: AbstractMatch
149149
regex::Regex
150150
end
151151

152+
function keys(m::RegexMatch)
153+
idx_to_capture_name = PCRE.capture_names(m.regex.regex)
154+
return map(eachindex(m.captures)) do i
155+
# If the capture group is named, return it's name, else return it's index
156+
get(idx_to_capture_name, i, i)
157+
end
158+
end
159+
152160
function show(io::IO, m::RegexMatch)
153161
print(io, "RegexMatch(")
154162
show(io, m.match)
155-
idx_to_capture_name = PCRE.capture_names(m.regex.regex)
156-
if !isempty(m.captures)
163+
capture_keys = keys(m)
164+
if !isempty(capture_keys)
157165
print(io, ", ")
158-
for i = 1:length(m.captures)
159-
# If the capture group is named, show the name.
160-
# Otherwise show its index.
161-
capture_name = get(idx_to_capture_name, i, i)
166+
for (i, capture_name) in enumerate(capture_keys)
162167
print(io, capture_name, "=")
163168
show(io, m.captures[i])
164169
if i < length(m.captures)

test/regex.jl

+1
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,7 @@
9898
@test !haskey(m, "foo")
9999
@test (m[:a], m[2], m["b"]) == ("x", "y", "z")
100100
@test sprint(show, m) == "RegexMatch(\"xyz\", a=\"x\", 2=\"y\", b=\"z\")"
101+
@test keys(m) == ["a", 2, "b"]
101102
end
102103

103104
# Backcapture reference in substitution string

0 commit comments

Comments
 (0)