Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
  System.out.println(m.group());
}

... prints -2 and 12.


-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \ as \\ in a Java String though. So, \d+ matches 1 or more digits.

Answer from Sean Owen on Stack Overflow
🌐
DevQA
devqa.io › extract-numbers-string-java-regular-expressions
Extract Numbers From String Using Java Regular Expressions
February 11, 2020 - The following Java Regular Expression ... } } ... If you want to extract only certain numbers from a string you can provide an index to the group() function....
Discussions

Java REGEX for only numbers - Stack Overflow
Im working on a personal custom text editor for mysql and this is my issue: This is what im currently using, it will highlight any number, i want to exclude numbers directly concatenated to any le... More on stackoverflow.com
🌐 stackoverflow.com
Extract number from string using regex in java - Stack Overflow
I fail to extract a (double) number from a pre-defined input String using a regular expression. The String is: String inputline ="Neuer Kontostand";"+2.117,68"; For successfully parsing just the n... More on stackoverflow.com
🌐 stackoverflow.com
apex - How to find all numbers in a string using Regex - Salesforce Stack Exchange
I am trying to extract all numbers from a string but I got the below code to work although it stops after the first match for 123. String str = '123-456/7890'; Pattern p = Pattern.compile('(\\d+)... More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
July 25, 2014
Please help me with a RegEx to extract only the numbers from a string variable
Hi, I have a string variable which contains both text and numbers assigned to a string variable. I want to extract the numbers from the string using RegEx. Example: If the text is “Text#$1234”, I want to extract “1234” alone Thanks More on forum.uipath.com
🌐 forum.uipath.com
6
1
March 12, 2024
🌐
UI Bakery
uibakery.io › regex-library › numbers-only-regex-java
Numbers only regex (digits only) Java
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 // Extract real number from a string String[] matches = Pattern.compile("(?:-(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))|(?:0|(?:[1-9](?:\\d{0,2}(?:,\\d{3})+|\\d*))))(?:.\\d+|)") .matcher("Pi equals to 3.14") .results() .map(MatchResult::group) .toArray(String[]::new); System.out.println(Arrays.toString(matches)); // prints [3.14] } } Test it!
🌐
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 - We can use regular expressions to count occurrences of numbers in a String in Java. We look at finding numbers of various formats, extracting and converting them back into numeric form, as well as counting digits.
🌐
LinkedIn
linkedin.com › pulse › java-extract-number-from-string-rajesh-k
Java extract number from string
January 25, 2018 - As per above Java program,i have used one String which is having alphabets and numbers.In above example simply i have stored in another String i.e numeric's with replaceAll method for name string and used [^0-9] regular expression means retrieve ...
🌐
StackHowTo
stackhowto.com › home › java › how to extract numbers from a string with regex in java
How to extract numbers from a string with regex in Java - StackHowTo
October 12, 2021 - import java.util.regex.*; public ... want to extract only certain numbers from a string, you can provide the index of the numbers to extract to the group() function....
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-extract-numbers-from-a-string-using-regular-expressions
How to extract numbers from a string using regular expressions?
November 21, 2019 - Online Resume Builder · HR Interview ... "); String data = sc.nextLine(); //Regular expression to match digits in a string String regex = "\d+";...
Find elsewhere
🌐
Attacomsian
attacomsian.com › blog › java-extract-digits-from-string
How to extract digits from a string in Java
February 22, 2020 - Pattern pattern = Pattern.compile("[^0-9]"); String numberOnly = pattern.matcher(str).replaceAll("");
🌐
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:
🌐
YouTube
youtube.com › coffee programmer
How to extract Numbers from a String in Java using Regular Expressions - YouTube
Can you help me to buy a coffee:https://www.buymeacoffee.com/coffeeprogram
Published: March 29, 2023
Views: 709
🌐
GeeksforGeeks
geeksforgeeks.org › java › extract-all-integers-from-the-given-string-in-java
Extract all integers from the given String in Java - GeeksforGeeks
// Java program to extract integers from a string // using regex import java.util.regex.*; import java.util.*; public class Extract { public static void main(String[] args) { String i = "Java 123 is a Programming 456 Language."; // Compile the regex to match integers Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(i); // Extract integers List<Integer> n = new ArrayList<>(); while (matcher.find()) { n.add(Integer.parseInt(matcher.group())); } System.out.println("" + n); } }
Published: July 12, 2025
🌐
Javacodeexamples
javacodeexamples.com › home
betworld369 สล็อตเว็บตรง แตกหนัก รวมเกมสล็อตแตกบ่อย 2026
July 2, 2026 - betworld369 เว็บตรง ไม่ผ่านเอเย่นต์ ล่าสุดปี 2026 รองรับระบบฝากถอนทรูวอเลท สะดวกรวดเร็วใน 3 วินาที ปั่นสล็อตเบทเริ่มต้นเพียง 1 บาท
🌐
UiPath Community
forum.uipath.com › help › studio
Please help me with a RegEx to extract only the numbers from a string variable - Studio - UiPath Community Forum
March 12, 2024 - Hi, I have a string variable which contains both text and numbers assigned to a string variable. I want to extract the numbers from the string using RegEx. Example: If the text is “Text#$1234”, I want to extract “1234” …
🌐
Medium
medium.com › @sujathamudadla1213 › how-to-extract-numbers-from-a-long-string-in-java-b61ccbf85b76
How to extract numbers from a long string in Java | by Sujatha Mudadla | Medium
July 17, 2023 - Using Regular Expressions (Regex): You can use regex to match and extract numbers from the string. The Pattern and Matcher classes from the java.util.regex package are used for this purpose.
Top answer
1 of 13
420

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