Skip to content

Commit

Permalink
define keys on RegexMatch (JuliaLang#37299)
Browse files Browse the repository at this point in the history
  • Loading branch information
oxinabox authored and antoine-levitt committed May 9, 2021
1 parent 1e94d27 commit e9a46a5
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 6 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Standard library changes
* `escape_string` can now receive a collection of characters in the keyword
`keep` that are to be kept as they are. ([#38597]).
* `getindex` can now be used on `NamedTuple`s with multiple values ([#38878])
* `keys(::RegexMatch)` is now defined to return the capture's keys, by name if named, or by index if not ([#37299]).

#### Package Manager

Expand Down
17 changes: 11 additions & 6 deletions base/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -149,16 +149,21 @@ struct RegexMatch <: AbstractMatch
regex::Regex
end

function keys(m::RegexMatch)
idx_to_capture_name = PCRE.capture_names(m.regex.regex)
return map(eachindex(m.captures)) do i
# If the capture group is named, return it's name, else return it's index
get(idx_to_capture_name, i, i)
end
end

function show(io::IO, m::RegexMatch)
print(io, "RegexMatch(")
show(io, m.match)
idx_to_capture_name = PCRE.capture_names(m.regex.regex)
if !isempty(m.captures)
capture_keys = keys(m)
if !isempty(capture_keys)
print(io, ", ")
for i = 1:length(m.captures)
# If the capture group is named, show the name.
# Otherwise show its index.
capture_name = get(idx_to_capture_name, i, i)
for (i, capture_name) in enumerate(capture_keys)
print(io, capture_name, "=")
show(io, m.captures[i])
if i < length(m.captures)
Expand Down
1 change: 1 addition & 0 deletions test/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@
@test !haskey(m, "foo")
@test (m[:a], m[2], m["b"]) == ("x", "y", "z")
@test sprint(show, m) == "RegexMatch(\"xyz\", a=\"x\", 2=\"y\", b=\"z\")"
@test keys(m) == ["a", 2, "b"]
end

# Backcapture reference in substitution string
Expand Down

0 comments on commit e9a46a5

Please sign in to comment.