Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

define keys on RegexMatch #37299

Merged
merged 1 commit into from
Jan 21, 2021
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 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