diff --git a/base/regex.jl b/base/regex.jl index 1c94e245e3189d..5aa45fa43a12f9 100644 --- a/base/regex.jl +++ b/base/regex.jl @@ -168,6 +168,8 @@ function getindex(m::RegexMatch, name::Symbol) end getindex(m::RegexMatch, name::AbstractString) = m[Symbol(name)] +iterate(m::RegexMatch) = iterate(m.captures) + function occursin(r::Regex, s::AbstractString; offset::Integer=0) compile(r) return PCRE.exec_r(r.regex, String(s), offset, r.match_options) diff --git a/test/regex.jl b/test/regex.jl index 6a32a49051d139..6ad32b7d3109af 100644 --- a/test/regex.jl +++ b/test/regex.jl @@ -136,6 +136,24 @@ @test r"this|that"^2 == r"(?:this|that){2}" end + @testset "iterate" begin + m = match(r"(.) test (.+)", "a test 123") + @test first(m) == "a" + @test collect(m) == ["a", "123"] + @test for (i, capture) in m + i == 1 && @test capture == "a" + i == 2 && @test capture == "123" + end + end + + @testset "Destructuring dispatch" begin + handle(::Nothing) = "not found" + handle((capture,)::RegexMatch) = "found $capture" + + @test handle(match(r"a (\d)", "xyz")) == "not found" + @test handle(match(r"a (\d)", "a 1")) == "found 1" + end + # Test that PCRE throws the correct kind of error # TODO: Uncomment this once the corresponding change has propagated to CI #@test_throws ErrorException Base.PCRE.info(C_NULL, Base.PCRE.INFO_NAMECOUNT, UInt32)