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:

  • Java Regular Expressions

  • Java Character Escape Sequences


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());
Answer from vikingsteve on Stack Overflow
Top answer
1 of 13
421

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:

  • Java Regular Expressions

  • Java Character Escape Sequences


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());
2 of 13
35

You can also use NumberUtil.isNumber(String str) from Apache Commons

🌐
Blogger
javarevisited.blogspot.com › 2012 › 10 › regular-expression-example-in-java-to-check-String-number.html
How to check if a String is Number in Java - Regular Expression Example
In order to check for digits you can either use character class [0-9] or use short-form \d. here is a simple regular expression in Java which can check if a String contains 6 digits or not:
🌐
Java67
java67.com › 2014 › 01 › java-regular-expression-to-check-numbers-in-String.html
Java Regular Expression to Check If String contains at least One Digit | Java67
\d is a character class for matching digits, and since backward slash needs to escaped in Java, we have put another backslash e.g. \\d.. So if you read this regular expression, it days any character any number of time, followed by any digit ...
🌐
DevQA
devqa.io › extract-numbers-string-java-regular-expressions
Extract Numbers From String Using Java Regular Expressions
February 11, 2020 - import java.util.regex.Matcher; ...n(matcher.group(1)); } } } Output: 9999 · You can use Java regular expressions to extract a part of a String which contains digits and characters....
🌐
UI Bakery
uibakery.io › regex-library › numbers-only-regex-java
Numbers only regex (digits only) Java
Real number regex can be used to validate or exact real numbers from a string. Pattern.compile("^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$") ... import java.util.regex.Pattern; import java.util.regex.MatchResult; import java.util.Arrays; public class Main { public static void main(String []args) { // Validate real number boolean isMatch = Pattern.compile("^(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)$") .matcher("121220.22") .find(); System.out.println(isMatch); // prints true // Ext
🌐
Coderanch
coderanch.com › t › 653258 › java › method-string-digit
What method to use to see if a string contains at least one digit? [Solved] (Beginning Java forum at Coderanch)
July 30, 2015 - So that is anything any number of times then digit then anything any number of times. Any number includes 0. Your suggestion works for matches() and find(). If you can accept only using find() then "\\d" will suffice. JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-check-if-string-contains-only-digits-in-java
How to Check if a String Contains only Digits in Java? - GeeksforGeeks
The matches() method returns true if the string matches the regex. In this method, the idea is to traverse each character in the string and check if the character of the string contains only digits from 0 to 9. If all the character of the string ...
Published: July 15, 2025
Find elsewhere
🌐
Jenkov
jenkov.com › tutorials › java-regex › index.html
Java Regex - Java Regular Expressions
March 5, 2019 - Since the \ character is also an ... in the Java string to get a \d in the regular expression. Here is how such a regular expression string looks: ... This regular expression will match strings starting with "Hi" followed by a digit (0 to 9). Thus, it will match the string "Hi5" but not the string "Hip". Matching non-digits can be done with the predefined character class [\D] (uppercase D). Here is an regular expression containing the non-digit ...
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-match-digits-using-java-regular-expression-regex
How to match digits using Java Regular Expression (RegEx)
November 19, 2019 - You can match digits in a given string using the meta character "\d" or by using the following expression : [0-9] import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static ...
Top answer
1 of 6
12

You could use Pattern instead, I think "matches" method looks for the whole string to match the regular expression.

Try the next code:

    int combinations = 0;
    String pass = "!!AAabas1";
    if (Pattern.compile("[0-9]").matcher(pass).find()) {
        combinations = combinations + 10;
    }

    if (Pattern.compile("[a-z]").matcher(pass).find()) {
        combinations = combinations + 26;
    }

    if (Pattern.compile("[A-Z]").matcher(pass).find()) {
        combinations = combinations + 26;
    }
2 of 6
4

Here's my attempt. Note, this uses unicode categories for validation so is non-latin language friendly.

import java.util.regex.Pattern;

public class PasswordValidator {

    public static void main(String[] args) {
        final PasswordValidator passwordValidator = new PasswordValidator();
        for (String password : new String[] { "abc", "abc123", "ABC123", "abc123ABC", "!!!AAabas1", "гшщз",
                "гшщзЧСМИ22" }) {
            System.out.printf("Password '%s' is %s%n", password, passwordValidator.isValidPassword(password) ? "ok"
                    : "INVALID");
        }
    }
    private static final Pattern LOWER_CASE = Pattern.compile("\\p{Lu}");
    private static final Pattern UPPER_CASE = Pattern.compile("\\p{Ll}");
    private static final Pattern DECIMAL_DIGIT = Pattern.compile("\\p{Nd}");

    /**
     * Determine if a password is valid.
     * 
     * <p>
     * A password is considered valid if it contains:
     * <ul>
     * <li>At least one lower-case letter</li>
     * <li>At least one upper-case letter</li>
     * <li>At least one digit</li>
     * </p>
     * 
     * @param password
     *            password to validate
     * @return True if the password is considered valid, otherwise false
     */
    public boolean isValidPassword(final String password) {
        return containsDigit(password) && containsLowerCase(password) && containsUpperCase(password);
    }

    private boolean containsDigit(final String str) {
        return DECIMAL_DIGIT.matcher(str).find();
    }

    private boolean containsUpperCase(final String str) {
        return UPPER_CASE.matcher(str).find();
    }

    private boolean containsLowerCase(final String str) {
        return LOWER_CASE.matcher(str).find();
    }

}

Here's the output:

Password 'abc' is INVALID
Password 'abc123' is INVALID
Password 'ABC123' is INVALID
Password 'abc123ABC' is ok
Password '!!!AAabas1' is ok
Password 'гшщз' is INVALID
Password 'гшщзЧСМИ22' is ok
🌐
Dirask
dirask.com › posts › Java-check-if-string-contains-any-numbers-D6Mdq1
Java - check if string contains any numbers
import java.util.regex.Matcher; ... loops through the string and checks if any character is a digit with Character.isDigit(char ch) method....
🌐
Vogella
vogella.com › tutorials › JavaRegularExpressions › article.html
Regular expressions in Java - Tutorial
The following example will check if a text contains a number with 3 digits. Create the Java project de.vogella.regex.numbermatch and the following class.
🌐
NTU Singapore
www3.ntu.edu.sg › home › ehchua › programming › howto › Regexe.html
Regular Expression (Regex) Tutorial
You can also write \d+, where \d is known as a meta-character that matches any digit (same as [0-9]). There are more than one ways to write a regex! Take note that many programming languages (C, Java, JavaScript, Python) use backslash \ as the prefix for escape sequences (e.g., \n for newline), and you need to write "\\d+" instead.