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.
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 - public static String extractNumbers(String input) { String[] words = input.split(โ\\s+โ); StringBuilder numbers = new StringBuilder(); for (String word : words) { try { int number = Integer.parseInt(word); numbers.append(number).append(โ ...
java - How to extract numbers from a string and get an array of ints? - Stack Overflow
I have a String variable (basically an English sentence with an unspecified number of numbers) and I'd like to extract all the numbers into an array of integers. I was wondering whether there was a... More on stackoverflow.com
Extract digits from string - StringUtils Java - Stack Overflow
(for those who will ask, I have ... specific number within it) I would like to use the StringUtils class from Apache commomns. ... Apache StringUtils. Not sure why you wanna use it though. ... That's what I have, was wondering if maybe there is a function already doing something like I need, but I am not so familiar with it ... Cuz, when you can do it with String itself, you won't need the StringUtils from Apache. ... This question is similar to: Extract digits from a string in Java... More on stackoverflow.com
How to extract numbers from string in java - Stack Overflow
A program that I write recives an input like this W 12.1 -1 2.2 B 1.2 3.2 1 And I need to check if the numbers are within coonstraints, so my idea is to store those numbers in array as integers. ... More on stackoverflow.com
how to extract numeric values from input string in java - Stack Overflow
How can I extract only the numeric values from the input string? For example, the input string may be like this: String str="abc d 1234567890pqr 54897"; I want the numeric values only i.e, "12345... More on stackoverflow.com
05:16
Extract Digits Program | ICSE Computer Applications | Java & BlueJ ...
01:54
How to extract numbers or alphabets from a String in Java? - YouTube
11:16
How to Extract digits from String in Java | Programming for Selenium ...
07:07
How to Extract and Sum Digits in a String? | JAVA INTERVIEW QUESTIONS ...
Print each digit of a number on a separate line in Java | Java ...
06:44
How to extract Numbers from a String in Java using Regular ...
Top answer 1 of 13
187
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.
2 of 13
55
What about to use replaceAll java.lang.String method:
String str = "qwerty-1qwerty-2 455 f0gfg 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output:
[-1, -2, 455, 0, 4]
Description
[^-?0-9]+
[and]delimites a set of characters to be single matched, i.e., only one time in any order^Special identifier used in the beginning of the set, used to indicate to match all characters not present in the delimited set, instead of all characters present in the set.+Between one and unlimited times, as many times as possible, giving back as needed-?One of the characters โ-โ and โ?โ0-9A character in the range between โ0โ and โ9โ
IncludeHelp
includehelp.com โบ java-programs โบ extract-digits-numbers-from-string.aspx
Java program to extract digits/ numbers from the string
import java.util.Scanner; class ....print("Enter string that contains numbers: "); str=SC.nextLine(); //extracting string numbers=str.replaceAll("[^0-9]", ""); System.out.println("Numbers are: " + numbers); } }...
Top answer 1 of 16
212
Use this code numberOnly will contain your desired output.
String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");
2 of 16
40
I always like using Guava String utils or similar for these kind of problems:
String theDigits = CharMatcher.inRange('0', '9').retainFrom("abc12 3def"); // 123
GeeksforGeeks
geeksforgeeks.org โบ java โบ extract-all-integers-from-the-given-string-in-java
Extract all integers from the given String in Java - GeeksforGeeks
Apart from regular expressions, there are other effective methods to extract integers from a string. We will dicuss them below: This method iterates through each character in the string by identifying numeric characters, and building numbers step by step. ... // Java program to extract integers from a given string public class Extract { public static void main(String[] args) { String s = "abc123def456ghi"; StringBuilder r = new StringBuilder(); boolean wasDigit = false; // Flag to track if the previous character was a digit // Iterate through each character in the string for (char c : s.toChar
Published: July 12, 2025
javaspring
javaspring.net โบ blog โบ how-to-extract-numeric-values-from-input-string-in-java
How to Extract Numeric Values from a String in Java: Tutorial with Examples โ javaspring.net
Use java.util.regex.Pattern and Matcher to define patterns and find matches. ... import java.util.regex.*; import java.util.ArrayList; import java.util.List; public class RegexExample { public static List<String> extractNumbersWithRegex(String input) { List<String> numbers = new ArrayList<>(); // Pattern to match integers, decimals, and negatives Pattern pattern = Pattern.compile("[-+]?\\d*\\.?\\d+"); Matcher matcher = pattern.matcher(input); while (matcher.find()) { // Find all matches numbers.add(matcher.group()); // Add matched number to list } return numbers; } public static void main(String[] args) { String input = "Order 456: Total $-199.99, Quantity +3.5"; List<String> numbers = extractNumbersWithRegex(input); System.out.println("Extracted numbers: " + numbers); // Output: [456, -199.99, +3.5] } }
Silicon Cloud
silicloud.com โบ home โบ extract numbers from string in java: 2 methods
Extract Numbers from String in Java: 2 Methods - Blog - Silicon Cloud
August 5, 2025 - public class Main { public static void main(String[] args) { String str = "abc123def456"; StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (Character.isDigit(c)) { sb.append(c); } } String numbers = sb.toString(); System.out.println(numbers); } } The choice between these two methods for extracting numbers from a string depends on the specific requirements and format of the string. #Java programming basics #java regex tutorial #Java string manipulation #java string parsing #number extraction java
Stack Overflow
stackoverflow.com โบ questions โบ 45266276 โบ how-to-extract-numbers-from-string-in-java
How to extract numbers from string in java - Stack Overflow
Split on the delimiter (whitespace, split("\\s")) and then process each element and check whether it is a number. You can do so manually or with a simple regex match like -?\\d+\\.?\\d+ or by trying to parse it with Integer#parseInt, ...
Tutorjoes
tutorjoes.in โบ Java_example_programs โบ extract_numbers_from_the_string_in_java
Write Java program to Extract Numbers from the string
System.out.println() method, along with a descriptive message. import java.util.Scanner; class Extract_Numbers { public static void main(String[] args) { String str, num; Scanner input = new Scanner(System.in); System.out.print("Enter the Paragraphs : "); str = input.nextLine(); num = ...
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 - For example, if we want to extract only the second number of the string โstr54776str917str78001strโ, which is 917, we can use the following code: import java.util.regex.*; public class Main { public static void main(String[] args) { Pattern pattern = Pattern.compile("[^\\d]*[\\d]+[^\\d]+([\\d]+)"); Matcher matcher = pattern.matcher("str54776str917str78001str"); if (matcher.find()) { // second matching number System.out.println(matcher.group(1)); } } }
CodingTechRoom
codingtechroom.com โบ question โบ -extract-number-from-string-java
How to Extract a Number from a String in Java? - CodingTechRoom
Mistake: Ignoring multiple numbers in a string and only retrieving the first match. Solution: Use a loop with matcher.find() to extract all occurrences. ... A broad desk reference for the Java language and standard library.
Sanfoundry
sanfoundry.com โบ java-program-extract-digits-given-integer
Java Program to Extract Digits from a Given Number - Sanfoundry
May 23, 2022 - Here is the source code of the Java Program to Extract Digits from A Given Integer. The Java program is successfully compiled and run on a Windows system. The program output is also shown below. ... $ javac Extract_Digits.java $ java Extract_Digits Enter any number:5678 Digits at position 4:8 Digits at position 3:7 Digits at position 2:6 Digits at position 1:5
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 - You can match numbers in the given string using either of the following regular expressions โ ยท โ\d+โ Or, "([0-9]+)" import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractingDigits { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter sample text: "); String data = sc.nextLine(); //Regular expression to match digits in a string String regex = "\d+"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Creating a Matcher object Matcher matcher = pattern.matcher(data); System.out.println("Digits in the given string are: "); while(matcher.find()) { System.out.print(matcher.group()+" "); } } } Enter sample text: this is a sample 23 text 46 with 11223 numbers in it Digits in the given string are: 23 46 11223 ยท
Top answer 1 of 16
23
You could use the .nextInt() method from the Scanner class:
Scans the next token of the input as an int.
Alternatively, you could also do something like so:
String str=" abc d 1234567890pqr 54897";
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher(str);
while(m.find())
{
System.out.println(m.group(1));
}
2 of 16
14
String str=" abc d 1234567890pqr 54897";
Pattern pattern = Pattern.compile("\\w+([0-9]+)\\w+([0-9]+)");
Matcher matcher = pattern.matcher(str);
for(int i = 0 ; i < matcher.groupCount(); i++) {
matcher.find();
System.out.println(matcher.group());
}