Skip to content

Commit

Permalink
make haskey with Integers work with RegexMatch (#37300)
Browse files Browse the repository at this point in the history
  • Loading branch information
oxinabox authored Sep 1, 2020
1 parent 01e4819 commit 0c66483
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 0 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ Standard library changes
* `intersect` on `CartesianIndices` now returns `CartesianIndices` instead of `Vector{<:CartesianIndex}` ([#36643]).
* `push!(c::Channel, v)` now returns channel `c`. Previously, it returned the pushed value `v` ([#34202]).
* `RegexMatch` objects can now be probed for whether a named capture group exists within it through `haskey()` ([#36717]).
* For consistency `haskey(r::RegexMatch, i::Integer) has also been added and returns if the capture group for `i` exists ([#37300]).
* A new standard library `TOML` has been added for parsing and printing [TOML files](https://toml.io) ([#37034]).

#### LinearAlgebra
Expand Down
2 changes: 2 additions & 0 deletions base/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,8 @@ function getindex(m::RegexMatch, name::Symbol)
m[idx]
end
getindex(m::RegexMatch, name::AbstractString) = m[Symbol(name)]

haskey(m::RegexMatch, idx::Integer) = idx in eachindex(m.captures)
function haskey(m::RegexMatch, name::Symbol)
idx = PCRE.substring_number_from_name(m.regex.regex, name)
return idx > 0
Expand Down
10 changes: 10 additions & 0 deletions test/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@
@test count(r"\w*", "foo bar") == 4
@test count(r"\b", "foo bar") == 4

# Unnamed subpatterns
let m = match(r"(.)(.)(.)", "xyz")
@test haskey(m, 1)
@test haskey(m, 2)
@test haskey(m, 3)
@test !haskey(m, 44)
@test (m[1], m[2], m[3]) == ("x", "y", "z")
@test sprint(show, m) == "RegexMatch(\"xyz\", 1=\"x\", 2=\"y\", 3=\"z\")"
end

# Named subpatterns
let m = match(r"(?<a>.)(.)(?<b>.)", "xyz")
@test haskey(m, :a)
Expand Down

0 comments on commit 0c66483

Please sign in to comment.