@@ -328,26 +328,58 @@ findfirst(r::Regex, s::AbstractString) = findnext(r,s,firstindex(s))
328
328
329
329
330
330
"""
331
- findall(pattern::Union{AbstractString,Regex}, string::AbstractString; overlap::Bool=false)
331
+ findall(
332
+ pattern::Union{AbstractString,Regex},
333
+ string::AbstractString;
334
+ overlap::Bool = false,
335
+ )
332
336
333
337
Return a `Vector{UnitRange{Int}}` of all the matches for `pattern` in `string`.
334
338
Each element of the returned vector is a range of indices where the
335
339
matching sequence is found, like the return value of [`findnext`](@ref).
336
340
337
341
If `overlap=true`, the matching sequences are allowed to overlap indices in the
338
- original string, otherwise they must be from distinct character ranges.
342
+ original string, otherwise they must be from disjoint character ranges.
339
343
"""
340
344
function findall (t:: Union{AbstractString,Regex} , s:: AbstractString ; overlap:: Bool = false )
341
345
found = UnitRange{Int}[]
342
346
i, e = firstindex (s), lastindex (s)
343
347
while true
344
348
r = findnext (t, s, i)
345
- isnothing (r) && return found
349
+ isnothing (r) && break
346
350
push! (found, r)
347
351
j = overlap || isempty (r) ? first (r) : last (r)
348
- j > e && return found
352
+ j > e && break
353
+ @inbounds i = nextind (s, j)
354
+ end
355
+ return found
356
+ end
357
+
358
+ """
359
+ count(
360
+ pattern::Union{AbstractString,Regex},
361
+ string::AbstractString;
362
+ overlap::Bool = false,
363
+ )
364
+
365
+ Return the number of matches for `pattern` in `string`. This is equivalent to
366
+ calling `length(findall(pattern, string))` but more efficient.
367
+
368
+ If `overlap=true`, the matching sequences are allowed to overlap indices in the
369
+ original string, otherwise they must be from disjoint character ranges.
370
+ """
371
+ function count (t:: Union{AbstractString,Regex} , s:: AbstractString ; overlap:: Bool = false )
372
+ n = 0
373
+ i, e = firstindex (s), lastindex (s)
374
+ while true
375
+ r = findnext (t, s, i)
376
+ isnothing (r) && break
377
+ n += 1
378
+ j = overlap || isempty (r) ? first (r) : last (r)
379
+ j > e && break
349
380
@inbounds i = nextind (s, j)
350
381
end
382
+ return n
351
383
end
352
384
353
385
"""
0 commit comments