http://stackoverflow.com/questions/15111420/how-to-check-if-a-string-contains-only-digits-in-java


Q:

In Java for String class there is a method called matches, how to use this method to check if my string is having only digits using regular expression. I tried with below examples, but both of them returned me false as result.

String regex = "[0-9]"; String data = "23343453"; System.out.println(data.matches(regex));


String regex = "^[0-9]"; String data = "23343453";System.out.println(data.matches(regex));


Answer:

Try

String regex = "[0-9]+";

or

String regex = "\\d+";

Where the + means "one or more" and \d means "digit".

Note: the "double slash" gives you one slash. "\\d" gives you: \d


You must allow for more than a digit (the + sign) as in:

String regex = "[0-9]+"; 
String data = "23343453"; 
System.out.println(data.matches(regex));


Answer:

http://www.pretechsol.com/2013/10/how-to-check-if-string-contains-only.html#.UmgRIxAVuPA

private static boolean isNumber(final String number) {

        boolean bisNumber = false;

        if (number == null) {

            bisNumber = false;

        }

        try {

            Integer.parseInt(number);

            bisNumber = true;

        } catch (NumberFormatException ne) {

            bisNumber = false;

        }

        return bisNumber;

    }