Check if string is a number

How to check if a string consists of numbers only?

+3
source share
4 answers

For example, using the re module :

1> re:run("1234a56", "^[0-9]*$").
nomatch
2> re:run("123456", "^[0-9]*$"). 
{match,[{0,6}]}

Or using a list comprehension:

[Char || Char <- String, Char < $0 orelse Char > $9] == [].

Note that both solutions will consider accepting an empty list.

+2
source

One way is to convert it to an integer, and if that fails, you will find out that it is not an integer.

is_integer(S) ->
    try
        _ = list_to_integer(S),
        true
    catch error:badarg ->
        false
    end.

Or you can just check all the numbers, but you need to check the case of the edge of the empty list:

is_integer("") ->
    false;
is_integer(S) ->
    lists:all(fun (D) -> D >= $0 andalso D =< $9 end, S).
+4
source

.

+3
not lists:any(fun(C)->C < $0 or C > $9 end, YourString).

, , list_to_integer, , , . , "any" vs "" - , , , C.

+1

Source: https://habr.com/ru/post/1782213/


All Articles