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

expose findall for Vector{UInt8} #45307

Merged
merged 5 commits into from
May 27, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
24 changes: 24 additions & 0 deletions base/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,11 @@ findfirst(r::Regex, s::AbstractString) = findnext(r,s,firstindex(s))
string::AbstractString;
overlap::Bool = false,
)
findall(
pattern::Vector{UInt8}
string::Vector{UInt8};
Moelf marked this conversation as resolved.
Show resolved Hide resolved
overlap::Bool = false,
)

Return a `Vector{UnitRange{Int}}` of all the matches for `pattern` in `string`.
Each element of the returned vector is a range of indices where the
Expand All @@ -467,6 +472,11 @@ julia> findall("a", "banana")
2:2
4:4
6:6

julia> findall(UInt8[1,2], UInt8[1,2,3,1,2])
2-element Vector{UnitRange{Int64}}:
1:2
4:5
```

!!! compat "Julia 1.3"
Expand All @@ -486,6 +496,20 @@ function findall(t::Union{AbstractString,AbstractPattern}, s::AbstractString; ov
return found
end

function findall(t::T, s::T; overlap::Bool=false) where {T <: Vector{UInt8}}
Moelf marked this conversation as resolved.
Show resolved Hide resolved
found = UnitRange{Int}[]
i, e = firstindex(s), lastindex(s)
while true
r = findnext(t, s, i)
isnothing(r) && break
push!(found, r)
j = overlap || isempty(r) ? first(r) : last(r)
j > e && break
@inbounds i = nextind(s, j)
end
return found
end

"""
findall(c::AbstractChar, s::AbstractString)

Expand Down
4 changes: 4 additions & 0 deletions test/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@
@test findall('→', "OH⁻ + H₃CBr → HOH₃CBr⁻ → HOCH₃ + Br⁻") == [17, 35]
@test findall('a', "") == Int[]
@test findall('c', "batman") == Int[]
@test findall([0x52, 0x62], [0x40, 0x52, 0x62, 0x63]) == [2:3]
@test findall([0x52, 0x62], [0x40, 0x52, 0x62, 0x63, 0x52, 0x64]) == [2:3, 5:6]
Moelf marked this conversation as resolved.
Show resolved Hide resolved
@test findall([0x01, 0x01], [0x01, 0x01, 0x01, 0x01]) == [1:2, 3:4]
@test findall([0x01, 0x01], [0x01, 0x01, 0x01, 0x01]; overlap=true) == [1:2, 2:3, 3:4]

# count
@test count(r"\w+", "foo bar") == 2
Expand Down