5

How to test if a string is composed only of digits ?

Bertaud
  • 2,888
  • 5
  • 35
  • 48

5 Answers5

5

One way is to convert it to an integer and if that fails then you'll know it's not an integer.

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

Or you can just check all of the digits, but you do have to check the edge case of an empty list:

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

For example, using the re module:

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

Or, using list comprehension:

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

Note that both solutions will consider the empty list valid input.

Roberto Aloi
  • 30,570
  • 21
  • 75
  • 112
2

Use a regular expression.

duffymo
  • 305,152
  • 44
  • 369
  • 561
2
not lists:any(fun(C)->C < $0 or C > $9 end, YourString).

In production, though, I would agree with the list_to_integer as it's probably better optimized. I'm not sure whether there are different traversal characteristics on 'any' vs 'all' either - you could implement each of them in terms of the other, but they're probably both implemented in C.

Chris Hagan
  • 2,437
  • 3
  • 17
  • 16
1

Erlang doesn't come with a way to say if a string represents a numeric value or not, but does come with the built-in function is_number/1, which will return true if the argument passed is either an integer or a float. Erlang also has two functions to transform a string to either a floating number or an integer, which will be used in conjunction with is_number/1.

is_numeric(L) ->
    Float = (catch erlang:list_to_float(L)),
    Int = (catch erlang:list_to_integer(L)),
    is_number(Float) orelse is_number(Int).

https://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Erlang

netotz
  • 193
  • 1
  • 4
  • 12