Correct usage of regex matches

Hey, I am quite new to Julia and come from an R background. I was wondering what the correct (or maybe short/julian way) to solve a simple regex matching problem would be. I have included a minimal working example below, but the solutions seems complicated to me. My main gripe is that I did not find a solution to access the matches (m.matches) in a vectorized manner (I expected some method to be available when I call m.matches where m is a vector of regex matches).

my_strings = ["anystring","question1","question29","somestring","someotherstring"]

m = match.(r"question[0-9]+",my_strings)

m = filter(x -> !isnothing(x), m)

my_result = [m[i].match for i in 1:length(m)]

I can only think of a very slight improvement

filter(x->!isnothing(x),m1) .|> (x->x.match)

1 Like

Could use an array comprehension with an if inside

julia> my_strings = ["anystring","question1","question29","somestring","someotherstring"];

julia> r = r"question[0-9]+";

julia> [x.match for x in (match(r, m) for m in my_strings) if x !== nothing]
2-element Vector{SubString{String}}:
 "question1"
 "question29
3 Likes

can be written !isnothing.

1 Like

Thanks for the comments! I really like both the array comprehension and the vector pipe with the anonymous function, but would probably prefer the latter since it seems a bit more readable to me (at the moment). But I will certainly try to find more use cases for array comprehensions in my code in the future!

Personally I would prefer findfirst:

filter(my_strings) do s
    !isnothing(findfirst(r"^question[0-9]+$", s))
end