Skip to content

Commit e6794e1

Browse files
committed
Make RegexMatch iterable
1 parent aa35ee2 commit e6794e1

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

base/regex.jl

+2
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,8 @@ function getindex(m::RegexMatch, name::Symbol)
168168
end
169169
getindex(m::RegexMatch, name::AbstractString) = m[Symbol(name)]
170170

171+
iterate(m::RegexMatch) = iterate(m.captures)
172+
171173
function occursin(r::Regex, s::AbstractString; offset::Integer=0)
172174
compile(r)
173175
return PCRE.exec_r(r.regex, String(s), offset, r.match_options)

test/regex.jl

+18
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,24 @@
136136
@test r"this|that"^2 == r"(?:this|that){2}"
137137
end
138138

139+
@testset "iterate" begin
140+
m = match(r"(.) test (.+)", "a test 123")
141+
@test first(m) == "a"
142+
@test collect(m) == ["a", "123"]
143+
@test for (i, capture) in m
144+
i == 1 && @test capture == "a"
145+
i == 2 && @test capture == "123"
146+
end
147+
end
148+
149+
@testset "Destructuring dispatch" begin
150+
handle(::Nothing) = "not found"
151+
handle((capture,)::RegexMatch) = "found $capture"
152+
153+
@test handle(match(r"a (\d)", "xyz")) == "not found"
154+
@test handle(match(r"a (\d)", "a 1")) == "found 1"
155+
end
156+
139157
# Test that PCRE throws the correct kind of error
140158
# TODO: Uncomment this once the corresponding change has propagated to CI
141159
#@test_throws ErrorException Base.PCRE.info(C_NULL, Base.PCRE.INFO_NAMECOUNT, UInt32)

0 commit comments

Comments
 (0)