Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make RegexMatch iterable #34355

Merged
merged 1 commit into from
Jan 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -47,6 +47,7 @@ Standard library changes
`keep` that are to be kept as they are. ([#38597]).
* `getindex` can now be used on `NamedTuple`s with multiple values ([#38878])
* `keys(::RegexMatch)` is now defined to return the capture's keys, by name if named, or by index if not ([#37299]).
* `RegexMatch` now iterate to give their captures. ([#34355]).

#### Package Manager

6 changes: 5 additions & 1 deletion base/regex.jl
Original file line number Diff line number Diff line change
@@ -166,7 +166,7 @@ function show(io::IO, m::RegexMatch)
for (i, capture_name) in enumerate(capture_keys)
print(io, capture_name, "=")
show(io, m.captures[i])
if i < length(m.captures)
if i < length(m)
print(io, ", ")
end
end
@@ -190,6 +190,10 @@ function haskey(m::RegexMatch, name::Symbol)
end
haskey(m::RegexMatch, name::AbstractString) = haskey(m, Symbol(name))

iterate(m::RegexMatch, args...) = iterate(m.captures, args...)
length(m::RegexMatch) = length(m.captures)
eltype(m::RegexMatch) = eltype(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)
18 changes: 18 additions & 0 deletions test/regex.jl
Original file line number Diff line number Diff line change
@@ -167,6 +167,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"]
for (i, capture) in enumerate(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)