Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index of all regex matches in Julia?

Tags:

regex

julia

I'm looking for a function that behaves like matchall() but returns an array containing the match index not the string?

like image 776
Dom Avatar asked Jan 18 '17 16:01

Dom


2 Answers

Thanks answer from Alexander Morley. And you can use findall() to get UnitRange of regex.

julia> findall(r"[0-9]+","aaaa1aaaa22aaaa333")
3-element Array{UnitRange{Int64},1}:
 5:5
 10:11
 16:18

In addition, if you want get string by regex, you can use SubString()

julia> s="aaaa1aaaa22aaaa333" ;

julia> SubString.(s, findall(r"[0-9]+",s))
3-element Array{SubString{String},1}:
 "1"
 "22"
 "333"

(Above codes tested on v1.3.0)

like image 132
sppmg Avatar answered Oct 20 '22 10:10

sppmg


eachmatch will give you an iterator over the regex matches.

So then with a list comprehension you could do this e.g.

[x.offset for x in eachmatch(r"[0-9]","aaaa1aaaa2aaaa3")]

or this

map(x->getfield(x,:offset), eachmatch(r"[0-9]","aaaa1aaaa2aaaa3"))

or even this...

getfield.(collect(eachmatch(r"[0-9]","aaaa1aaaa2aaaa3")), [:offset])

All returning:

3-element Array{Int64,1}:
  5
 10
 15
like image 17
Alexander Morley Avatar answered Oct 20 '22 10:10

Alexander Morley