From 0fd02fbb9bfd1d7b1e7bd65ff0df4a4e1604f650 Mon Sep 17 00:00:00 2001 From: Lyndon White Date: Tue, 19 Jan 2021 11:53:40 +0000 Subject: [PATCH] define keys on RegexMatch add to News.md about defining keys on RegexMatch fix whitespace return a Vector from keys(::RegexMatch) correct test of RegexMatch keys regex keys displayed are strings (since that is how we get them from PCRE) --- NEWS.md | 1 + base/regex.jl | 17 +++++++++++------ test/regex.jl | 1 + 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/NEWS.md b/NEWS.md index 61f3eb4fb8867..d994c3d2f17fc 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 diff --git a/base/regex.jl b/base/regex.jl index 3b954c53fd7ab..ff07b61bdec0d 100644 --- a/base/regex.jl +++ b/base/regex.jl @@ -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) diff --git a/test/regex.jl b/test/regex.jl index 77a7545eaecef..f5080bd3e6600 100644 --- a/test/regex.jl +++ b/test/regex.jl @@ -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