Skip to content

Commit

Permalink
Make RegexMatch iterable
Browse files Browse the repository at this point in the history
  • Loading branch information
oxinabox committed Jan 12, 2020
1 parent aa35ee2 commit e6794e1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
2 changes: 2 additions & 0 deletions base/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions test/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit e6794e1

Please sign in to comment.