Skip to content

Commit

Permalink
Add haskey(::RegexMatch, ::Symbol) to test for named capture groups (
Browse files Browse the repository at this point in the history
  • Loading branch information
staticfloat authored and simeonschaub committed Aug 11, 2020
1 parent a6a7282 commit 3491f2c
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 1 deletion.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ Standard library changes
* `first` and `last` functions now accept an integer as second argument to get that many
leading or trailing elements of any iterable ([#34868]).
* `intersect` on `CartesianIndices` now returns `CartesianIndices` instead of `Vector{<:CartesianIndex}` ([#36643]).
* `RegexMatch` objects can now be probed for whether a named capture group exists within it through `haskey()` ([#36717]).

#### LinearAlgebra
* New method `LinearAlgebra.issuccess(::CholeskyPivoted)` for checking whether pivoted Cholesky factorization was successful ([#36002]).
Expand Down
1 change: 0 additions & 1 deletion base/pcre.jl
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,6 @@ end
function substring_number_from_name(re, name)
n = ccall((:pcre2_substring_number_from_name_8, PCRE_LIB), Cint,
(Ptr{Cvoid}, Cstring), re, name)
n < 0 && error("PCRE error: $(err_message(n))")
return Int(n)
end

Expand Down
5 changes: 5 additions & 0 deletions base/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ function getindex(m::RegexMatch, name::Symbol)
m[idx]
end
getindex(m::RegexMatch, name::AbstractString) = m[Symbol(name)]
function haskey(m::RegexMatch, name::Symbol)
idx = PCRE.substring_number_from_name(m.regex.regex, name)
return idx > 0
end
haskey(m::RegexMatch, name::AbstractString) = haskey(m, Symbol(name))

function occursin(r::Regex, s::AbstractString; offset::Integer=0)
compile(r)
Expand Down
3 changes: 3 additions & 0 deletions test/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@

# Named subpatterns
let m = match(r"(?<a>.)(.)(?<b>.)", "xyz")
@test haskey(m, :a)
@test haskey(m, "b")
@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\")"
end
Expand Down

0 comments on commit 3491f2c

Please sign in to comment.