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

make haskey with Integers work with RegexMatch #37300

Merged
merged 3 commits into from
Sep 1, 2020
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 @@ -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