Parsing an integer

I want to be able to parse an integer only when it’s in the right format – when an input contains digits only.

An input comes from a user.

This is what I want to deal with:

iex(1)> Integer.parse("333aaa")
{333, "aaa"} # no, this isn't a right format for Integer!

I want to recognize such a situation and return an exception. Like here:

iex(2)> Integer.parse("bbb333aaa")
:error

iex(3)> Integer.parse("ccc3333")  
:error

How can I do this? Only with regexp?

Use String.to_integer or implement your own error handling like so:

case Integer.parse(str) do
  {num, ""} -> {:ok, num}
  {_, _}    -> # raise an error here
  _         -> # raise an error here as well
end
4 Likes

How can I combine the 2nd and 3rd cases into a single one with “or”?

All three cases are already “combined” using “or”, its either this, that, or anything.


edit Well, its more an order dependent XOR :wink:

How can I combine the 2nd and 3rd cases into a single one with “or”?

You mean, independently of which pattern matches, you want to return the same result/raise the same error?

Well, {_, _} is just a subset of _, so just drop the {_, _} clause…

1 Like