How to Extract Numbers from String in Java Easily
To extract numbers from a string in Java, use
String.replaceAll() with a regular expression to keep digits only, or use Pattern and Matcher classes to find numbers. These methods let you get all digits or separate numbers from mixed text easily.Syntax
There are two common ways to extract numbers from a string in Java:
- Using
String.replaceAll(): Replace all non-digit characters with an empty string to keep only numbers. - Using
PatternandMatcher: Use regex to find all sequences of digits in the string.
java
String numbersOnly = inputString.replaceAll("\\D", ""); Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(inputString);
Example
This example shows how to extract all digits as one string and how to find each number separately from a mixed string.
java
import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractNumbers { public static void main(String[] args) { String input = "Order123 has 45 items and costs 6789 dollars."; // Extract all digits as one string String digitsOnly = input.replaceAll("\\D", ""); System.out.println("All digits combined: " + digitsOnly); // Extract each number separately Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(input); System.out.print("Numbers found: "); while (matcher.find()) { System.out.print(matcher.group() + " "); } } }
Output
All digits combined: 123456789
Numbers found: 123 45 6789
Common Pitfalls
Common mistakes include:
- Using
replaceAll("\\d", "")which removes digits instead of keeping them. - Not escaping backslashes properly in regex strings.
- Assuming
replaceAllextracts separate numbers instead of one combined string.
Use Pattern and Matcher to get separate numbers.
java
String wrong = input.replaceAll("\\d", ""); // removes digits, wrong String right = input.replaceAll("\\D", ""); // keeps digits only // To get separate numbers, use Pattern and Matcher as shown in the example.
Quick Reference
Summary tips for extracting numbers from strings in Java:
- Keep digits only:
string.replaceAll("\\D", "") - Find separate numbers: Use
Pattern.compile("\\d+")andMatcher - Remember to escape backslashes: Use double backslashes in Java strings
Key Takeaways
Use
replaceAll("\\D", "") to extract all digits as one string.Use
Pattern and Matcher with regex "\\d+" to find separate numbers.Always escape backslashes in Java regex strings with double backslashes.
Avoid removing digits by mistake with incorrect regex patterns.
Choose method based on whether you want combined digits or separate numbers.