Skip to content

Commit c342ef8

Browse files
authored
Add haskey(::RegexMatch, ::Symbol) to test for named capture groups (#36717)
1 parent 45ac810 commit c342ef8

File tree

4 files changed

+9
-1
lines changed

4 files changed

+9
-1
lines changed

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ Standard library changes
7676
* `first` and `last` functions now accept an integer as second argument to get that many
7777
leading or trailing elements of any iterable ([#34868]).
7878
* `intersect` on `CartesianIndices` now returns `CartesianIndices` instead of `Vector{<:CartesianIndex}` ([#36643]).
79+
* `RegexMatch` objects can now be probed for whether a named capture group exists within it through `haskey()` ([#36717]).
7980

8081
#### LinearAlgebra
8182
* New method `LinearAlgebra.issuccess(::CholeskyPivoted)` for checking whether pivoted Cholesky factorization was successful ([#36002]).

base/pcre.jl

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,6 @@ end
194194
function substring_number_from_name(re, name)
195195
n = ccall((:pcre2_substring_number_from_name_8, PCRE_LIB), Cint,
196196
(Ptr{Cvoid}, Cstring), re, name)
197-
n < 0 && error("PCRE error: $(err_message(n))")
198197
return Int(n)
199198
end
200199

base/regex.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,11 @@ function getindex(m::RegexMatch, name::Symbol)
167167
m[idx]
168168
end
169169
getindex(m::RegexMatch, name::AbstractString) = m[Symbol(name)]
170+
function haskey(m::RegexMatch, name::Symbol)
171+
idx = PCRE.substring_number_from_name(m.regex.regex, name)
172+
return idx > 0
173+
end
174+
haskey(m::RegexMatch, name::AbstractString) = haskey(m, Symbol(name))
170175

171176
function occursin(r::Regex, s::AbstractString; offset::Integer=0)
172177
compile(r)

test/regex.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,9 @@
6666

6767
# Named subpatterns
6868
let m = match(r"(?<a>.)(.)(?<b>.)", "xyz")
69+
@test haskey(m, :a)
70+
@test haskey(m, "b")
71+
@test !haskey(m, "foo")
6972
@test (m[:a], m[2], m["b"]) == ("x", "y", "z")
7073
@test sprint(show, m) == "RegexMatch(\"xyz\", a=\"x\", 2=\"y\", b=\"z\")"
7174
end

0 commit comments

Comments
 (0)