Check if the string contains only numbers

Asked

Viewed 6,416 times

-3

How can I check if a string contains only numbers?

For example, you can’t have * / = e etc... only numbers.

Because I need to convert a string to int and if you type letters, symbols will generate an error.

  • 3

    Try to improve your question further by setting an example that you can and cannot and why!

2 answers

6


One of the ways to know if the string contains only numbers, is using a regular expression

"1239417".matches("[0-9]+");   // true
"12312a".matches("[0-9]+");    // false
"12312+".matches("[0-9]+");    // false

In regular expression [0-9]+

  • [ and ]: delimits a set of characters
  • 0-9: the character set, anyone between 0 and 9
  • +: of the defined expression, must correspond to 1 or more groups

2

Another way is to try the conversion to integer:

    String input = "123s";
    try {
        Integer.valueOf(input);
    } catch (Exception e) {
        System.out.println("Número inválido");
    }
  • 1

    I would only say to capture the specific exception.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.