Test if string begins with number

Dear all,
it is possible to test whether a string starts with a number?
Let’s say I have the following:

julia> x="Some string"
"Some string"

julia> y="1 Another string"
"1 Another string"

julia> X=x[1]
'S': ASCII/Unicode U+0053 (category Lu: Letter, uppercase)

julia> Y=y[1]
'1': ASCII/Unicode U+0031 (category Nd: Number, decimal digit)

julia> parse(Int8, X)
ERROR: ArgumentError: invalid base 10 digit 'S'
Stacktrace:
 [1] #parse#330(::Int64, ::Function, ::Type{Int8}, ::Char) at ./parse.jl:43
 [2] parse(::Type{Int8}, ::Char) at ./parse.jl:38
 [3] top-level scope at none:0

julia> parse(Int8, Y)
1

How can I distinguish between X and Y and determine that Y is a number?
Thank you

isdigit(X) && parse(Int8, X)

more generally, if you look for test functions, doing

julia> is\<tab>\<tab>

gives you a list of isX functions.

It is unclear if you want to check if a string starts with a number (ie something that would parse as a ::Real, or even broader, in Julia, eg "-12.7e9foo"), or simply a digit.

for the moment digit will do (thus the question is answered), but a more general approach might be handy in the future.

You have to be specific about how you want to generalize this; what would constitute valid strings, whether you need the number, etc. If you don’t, a regular expression can be used.

The more general approach you’re looking for is regex. Julia has regex functionality in Base, the relevant functions are listed here.

Be warned, regex notation is impossible to remember. :laughing:

regex notation is impossible to remember

Not anymore

To whoever it may concern, now the method startswith in the standard library accepts a regex as a prefix:

julia> startswith("1234 Hi!", r"\d+")
true

julia> startswith("1234 Hi!", r"\d")
true

julia> startswith("1234 Hi!", r"\w")
true

julia> startswith("1234 Hi!", r"[a-zA-Z]")
false

julia> startswith("1234 Hi!", r"[0-9]")
true