Skip to content

Commit 770d0d5

Browse files
oxinaboxomus
andauthored
Make RegexMatch iterable (#34355)
add iterate, length, and eltype to RegexMatch Co-authored-by: Curtis Vogt <[email protected]>
1 parent 1e775d7 commit 770d0d5

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

NEWS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ Standard library changes
4747
`keep` that are to be kept as they are. ([#38597]).
4848
* `getindex` can now be used on `NamedTuple`s with multiple values ([#38878])
4949
* `keys(::RegexMatch)` is now defined to return the capture's keys, by name if named, or by index if not ([#37299]).
50+
* `RegexMatch` now iterate to give their captures. ([#34355]).
5051

5152
#### Package Manager
5253

base/regex.jl

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ function show(io::IO, m::RegexMatch)
166166
for (i, capture_name) in enumerate(capture_keys)
167167
print(io, capture_name, "=")
168168
show(io, m.captures[i])
169-
if i < length(m.captures)
169+
if i < length(m)
170170
print(io, ", ")
171171
end
172172
end
@@ -190,6 +190,10 @@ function haskey(m::RegexMatch, name::Symbol)
190190
end
191191
haskey(m::RegexMatch, name::AbstractString) = haskey(m, Symbol(name))
192192

193+
iterate(m::RegexMatch, args...) = iterate(m.captures, args...)
194+
length(m::RegexMatch) = length(m.captures)
195+
eltype(m::RegexMatch) = eltype(m.captures)
196+
193197
function occursin(r::Regex, s::AbstractString; offset::Integer=0)
194198
compile(r)
195199
return PCRE.exec_r(r.regex, String(s), offset, r.match_options)

test/regex.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,24 @@
167167
@test r"this|that"^2 == r"(?:this|that){2}"
168168
end
169169

170+
@testset "iterate" begin
171+
m = match(r"(.) test (.+)", "a test 123")
172+
@test first(m) == "a"
173+
@test collect(m) == ["a", "123"]
174+
for (i, capture) in enumerate(m)
175+
i == 1 && @test capture == "a"
176+
i == 2 && @test capture == "123"
177+
end
178+
end
179+
180+
@testset "Destructuring dispatch" begin
181+
handle(::Nothing) = "not found"
182+
handle((capture,)::RegexMatch) = "found $capture"
183+
184+
@test handle(match(r"a (\d)", "xyz")) == "not found"
185+
@test handle(match(r"a (\d)", "a 1")) == "found 1"
186+
end
187+
170188
# Test that PCRE throws the correct kind of error
171189
# TODO: Uncomment this once the corresponding change has propagated to CI
172190
#@test_throws ErrorException Base.PCRE.info(C_NULL, Base.PCRE.INFO_NAMECOUNT, UInt32)

0 commit comments

Comments
 (0)