From 0c66483bf1890631fbe5e78d87d23b32b432b121 Mon Sep 17 00:00:00 2001 From: Lyndon White Date: Tue, 1 Sep 2020 23:04:50 +0100 Subject: [PATCH] make haskey with Integers work with RegexMatch (#37300) --- NEWS.md | 1 + base/regex.jl | 2 ++ test/regex.jl | 10 ++++++++++ 3 files changed, 13 insertions(+) diff --git a/NEWS.md b/NEWS.md index f5080a1448f11..f974f247e8ded 100644 --- a/NEWS.md +++ b/NEWS.md @@ -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 diff --git a/base/regex.jl b/base/regex.jl index 0625620969aa2..75c3777fd681a 100644 --- a/base/regex.jl +++ b/base/regex.jl @@ -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 diff --git a/test/regex.jl b/test/regex.jl index 59f4fd20932c0..4ee165a28bb7a 100644 --- a/test/regex.jl +++ b/test/regex.jl @@ -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"(?.)(.)(?.)", "xyz") @test haskey(m, :a)