javastringcharacterstring-matchingdigits

How to check if a string contains only digits in Java?


In Java for String class there is a method called matches. How to use this method to check if my string has 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));

Solution

  • Try

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

    or

    String regex = "\\d+";
    

    As per Java regular expressions, the + means "one or more times" and \d means "a digit".

    Note: the "double backslash" is an escape sequence to get a single backslash - therefore, \\d in a java String gives you the actual result: \d

    References:


    Edit: due to some confusion in other answers, I am writing a test case and will explain some more things in detail.

    Firstly, if you are in doubt about the correctness of this solution (or others), please run this test case:

    String regex = "\\d+";
    
    // positive test cases, should all be "true"
    System.out.println("1".matches(regex));
    System.out.println("12345".matches(regex));
    System.out.println("123456789".matches(regex));
    
    // negative test cases, should all be "false"
    System.out.println("".matches(regex));
    System.out.println("foo".matches(regex));
    System.out.println("aa123bb".matches(regex));
    

    Question 1:

    Isn't it necessary to add ^ and $ to the regex, so it won't match "aa123bb" ?

    No. In java, the matches method (which was specified in the question) matches a complete string, not fragments. In other words, it is not necessary to use ^\\d+$ (even though it is also correct). Please see the last negative test case.

    Please note that if you use an online "regex checker" then this may behave differently. To match fragments of a string in Java, you can use the find method instead, described in detail here:

    Difference between matches() and find() in Java Regex

    Question 2:

    Won't this regex also match the empty string, "" ?*

    No. A regex \\d* would match the empty string, but \\d+ does not. The star * means zero or more, whereas the plus + means one or more. Please see the first negative test case.

    Question 3

    Isn't it faster to compile a regex Pattern?

    Yes. It is indeed faster to compile a regex Pattern once, rather than on every invocation of matches, and so if performance implications are important then a Pattern can be compiled and used like this:

    Pattern pattern = Pattern.compile(regex);
    System.out.println(pattern.matcher("1").matches());
    System.out.println(pattern.matcher("12345").matches());
    System.out.println(pattern.matcher("123456789").matches());