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
🌐
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
🌐
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
This is similar to the above regex pattern, the only difference is \D is replaced by [^0-9]. By the way, there are always multiple ways to check for certain things using regex. This is a kind of special regular expression requirement for validating data like id, zipcode or any other pure numerical data. 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:
People also ask

Should I validate numbers using regex or Java types?
For format validation, regex is quick and flexible. For strict type validation, use Integer.parseInt() or Double.parseDouble() in Java.
🌐
qodex.ai
qodex.ai › all-tools › numbers-regex-java-validator
Numbers Regex Java Validator | Validate Numeric Patterns ...
What if a user enters commas in numbers?
Use a regex like ^\\d{1,3}(,\\d{3})*(\\.\\d+)?$ to support comma-separated formatting.
🌐
qodex.ai
qodex.ai › all-tools › numbers-regex-java-validator
Numbers Regex Java Validator | Validate Numeric Patterns ...
Can I validate both integers and decimals together?
Yes, you can use a regex like ^-?\\d+(\\.\\d+)?$ to match integers and optional decimals.
🌐
qodex.ai
qodex.ai › all-tools › numbers-regex-java-validator
Numbers Regex Java Validator | Validate Numeric Patterns ...
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

🌐
DevQA
devqa.io › extract-numbers-string-java-regular-expressions
Extract Numbers From String Using Java Regular Expressions
February 11, 2020 - To extract number 9999 we can use the following code: import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExamples { public static void main(String[]args) { Pattern pattern = Pattern.compile("numFound=\"([0-9]+)\""); Matcher matcher = pattern.matcher(""); if (matcher.find()) { System.out.println(matcher.group(1)); } } }
🌐
Stack Overflow
stackoverflow.com › questions › 36399594 › java-regex-match-number-pattern
Java regex match number pattern - Stack Overflow
import java.util.regex.Matcher; import java.util.regex.Pattern; public static void main(String[] args) { String input =" - 0\n"+ " - 100\n"+ " - 1,100.01\n"+ " - 100,100,3\n"+ " - 100,100,3.15\n"+ ""; refactorNumber(input); } public static void refactorNumber(String input){ Matcher m = Pattern.compile("((?:\\d,)?\\d{0,2}0(?:\\.\\d{1,2})?)(?!\\d*,)").matcher(input); while (m.find()) { //execute code } ... Here is a simple line of code I like to use to detect only numbers.
🌐
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 - import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Reading String from user System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "\d"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Number of digits: "+count); } } Enter a String sample text 1234 6657 Num
🌐
Baeldung
baeldung.com › home › java › core java › validate phone numbers with java regex
Validate Phone Numbers With Java Regex | Baeldung
January 8, 2024 - In the second example, let’s see how we can allow optional whitespace, dots, or hyphens (-) between the numbers: @Test public void whenMatchesTenDigitsNumberWhitespacesDotHyphen_thenCorrect() { Pattern pattern = Pattern.compile("^(\\d{3}[- .]?){2}\\d{4}$"); Matcher matcher = pattern.matcher("202 555 0125"); assertTrue(matcher.matches()); }
Find elsewhere
🌐
Qodex
qodex.ai › all-tools › numbers-regex-java-validator
Numbers Regex Java Validator | Validate Numeric Patterns ...
Java IP Regex Validator: Handle numeric ranges in IPs alongside numeric validations. Base64 Encoder: Encode numbers for secure data transfer or token generation. Yes, you can use a regex like ^-?\\d+(\\.\\d+)?$ to match integers and optional decimals. Yes, patterns like ^-?\\d+$ support optional negative signs.
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › regex › Pattern.html
Pattern (Java Platform SE 7 )
Unicode escape sequences such as \u2014 in Java source code are processed as described in section 3.3 of The Java™ Language Specification. Such escape sequences are also implemented directly by the regular-expression parser so that Unicode escapes can be used in expressions that are read from files or from the keyboard. Thus the strings "\u2014" and "\\u2014", while not equal, compile into the same pattern, which matches the character with hexadecimal value 0x2014.
🌐
W3Schools
w3schools.com › java › java_regex.asp
Java Regular Expressions
A regular expression can be a single character, or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations. Java does not have a built-in Regular Expression class, but we can import the java.util.regex package to work with ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › regular-expression-in-java-regex-example
Regular Expression in Java: Regex Examples & Tutorial | DigitalOcean
August 3, 2022 - You can create a group using (). The portion of input String that matches the capturing group is saved into memory and can be recalled using Backreference. You can use matcher.groupCount method to find out the number of capturing groups in a java regex pattern.
🌐
Vogella
vogella.com › tutorials › JavaRegularExpressions › article.html
Regular expressions in Java - Tutorial
This tutorial describes the usage of regular expressions in Java with modern examples and best practices. It covers basic regex syntax, Java’s Pattern and Matcher classes, practical examples for common use cases, and important security considerations.
🌐
Tutorialspoint
tutorialspoint.com › java › java_regular_expressions.htm
Java - Regular Expressions
Study methods review the input string and return a Boolean indicating whether or not the pattern is found − · Replacement methods are useful methods for replacing text in an input string − · Following is the example that counts the number of times the word "cat" appears in the input string − · import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexMatches { private static final String REGEX = "\\bcat\\b"; private static final String INPUT = "cat cat cat cattie cat"; public static void main( String args[] ) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object int count = 0; while(m.find()) { count++; System.out.println("Match number "+count); System.out.println("start(): "+m.start()); System.out.println("end(): "+m.end()); } } }
Top answer
1 of 2
2

You're using a Java flavor regex. The correct regex pattern would be:

^(?!26)([-()]*\d){5}[-()]*$

This one will make it so your input cannot start with 26. However, your post did not specify if it could be something like --2)6-218 (it doesn't start with 26, however the first two digits are 26. If this were the case, then you would need:

^(?![-()]*2[-()]*6)([-()]*\d){5}[-()]*$

The 10 character max should be validated on the input, maxlength=10.

Edit: as @zx81 pointed out, I had a few unnecessary escapes. I don't know what I was thinking, sorry. However, this regex pattern does not accept empty strings.

2 of 2
1

This regex will do what you want (see demo):

^(?!\D*(?:26|555))(?=(?:\D*\d){5}\D*$)[\d()-]{5,10}$

If you no longer want to reject 555, you can go with:

^(?!\D*26)(?=(?:\D*\d){5}\D*$)[\d()-]{5,10}$

And if 2--6123 is not allowed, change the regex to

^(?!\D*2[()-]*6)(?=(?:\D*\d){5}\D*$)[\d()-]{5,10}$

Explain Regex

^                        # the beginning of the string
(?!                      # look ahead to see if there is not:
  \D*                    #   non-digits (all but 0-9) (0 or more
                         #   times (matching the most amount
                         #   possible))
  (?:                    #   group, but do not capture:
    26                   #     '26'
   |                     #    OR
    555                  #     '555'
  )                      #   end of grouping
)                        # end of look-ahead
(?=                      # look ahead to see if there is:
  (?:                    #   group, but do not capture (5 times):
    \D*                  #     non-digits (all but 0-9) (0 or more
                         #     times (matching the most amount
                         #     possible))
    \d                   #     digits (0-9)
  ){5}                   #   end of grouping
  \D*                    #   non-digits (all but 0-9) (0 or more
                         #   times (matching the most amount
                         #   possible))
  $                      #   before an optional \n, and the end of
                         #   the string
)                        # end of look-ahead
[\d()-]{5,10}            # any character of: digits (0-9), '(', ')',
                         # '-' (between 5 and 10 times (matching the
                         # most amount possible))
$                        # before an optional \n, and the end of the
                         # string
🌐
CodingNConcepts
codingnconcepts.com › java › java-regex-to-validate-phone-number
Java Regex to Validate Phone Number - Coding N Concepts
May 27, 2020 - This Pattern will match mobile phone numbers with spaces and hyphen, as well as numbers like (987)6543210, (987) 654-3210, (987)-654-3210 etc. This regex is combined with regex to include parenthesis
🌐
JRebel
jrebel.com › blog › java-regular-expressions-cheat-sheet
Java Regular Expressions (Regex) Cheat Sheet | JRebel
July 30, 2025 - A Java regular expression, or Java Regex, is a sequence of characters that specifies a pattern which can be searched for in a text. A Regex defines a set of strings, usually united for a given purpose. Suppose you need a way to formalize and refer to all the strings that make up the format of an email address. Since there are a near infinite number ...
🌐
Baeldung
baeldung.com › home › java › java string › find all numbers in a string in java
Find All Numbers in a String in Java | Baeldung
June 24, 2025 - In regular expressions, “\d“ matches “any single digit”. Let’s use this expression to count digits in a string: int countDigits(String stringToSearch) { Pattern digitRegex = Pattern.compile("\\d"); Matcher countEmailMatcher = ...
🌐
Medium
medium.com › javarevisited › making-regex-your-friend-in-java-ddc5bf7f9a66
Tutorial on how regex works in Java | Javarevisited
September 21, 2021 - The first pattern uses only character classes, “+” (which is escaped because it has another meaning in regex) and “=”. The second pattern uses unnamed capturing groups. The final and third pattern uses named capturing groups. Note the syntax for named capturing groups: (?<NAME>pattern) The output from this is the following. Number of groups: 0 true Number of groups: 3 true 3+1=4 3 1 4 Number of groups: 3 true 3+1=4 3 1 4 3 1 4