How get only numbers from a string

I need get only numbers caracters from string

a = ["00023'4", "@00452a", "456ad52"]

Here’s one option:

julia> [filter(isdigit, collect(s)) for s in a]
3-element Vector{Vector{Char}}:
 ['0', '0', '0', '2', '3', '4']
 ['0', '0', '4', '5', '2']
 ['4', '5', '6', '5', '2']

Something like this?

julia> filter(x->'0'<=x<='9',"0123456789@3434341@!\$#%%^%\$#2343240")
"012345678934343412343240"
1 Like

@sudete has better altenative for digit checking by filter(isdigit, "0123456789@3434341@!\$#%%^%\$#2343240").

1 Like

Never use collect:

jl> [filter(isdigit, s) for s in a]
3-element Vector{String}:
 "000234"
 "00452"
 "45652"

or

jl> filter.(isdigit, a)
3-element Vector{String}:
 "000234"
 "00452"
 "45652"
1 Like

unless you actually want an array of characters :slight_smile:

It’s not completely clear what you want, so here are a couple of alternatives:

jl> a = ["00023'4", "@00452a", "456ad52"];

jl> [[m.match for m in eachmatch(r"\d+", str)] for str in a]
3-element Vector{Vector{SubString{String}}}:
 ["00023", "4"]
 ["00452"]
 ["456", "52"]

jl> [[parse(Int, m.match) for m in eachmatch(r"\d+", str)] for str in a]
3-element Vector{Vector{Int64}}:
 [23, 4]
 [452]
 [456, 52]

(BTW, I’m not very happy about the interface to regex matches, where you have to access the internal fields of the object, like it was Python, or something. Why aren’t there any methods for accessing the matched strings? This always seems un-idiomatic to me.)

Hmmmfff. Well, if you must, this is faster:

 filter!.(isdigit, collect.(a))

:wink: