Extract Digits from a String in Java using regular expression
In this post we show you how to use regular expressions to remove all non-digits characters of a String and return the number only String in Java application.
Following Java example code use String.replaceAll() method with regex “[^0-9]” to replace non-digits characters in a String with empty String.
public class ExtractDigitsFromStringExample1 {
public static void main(String[] args) {
String testString = "Java was released in 1995";
String numberOnlyString = testString.replaceAll("[^0-9]", "");
System.out.println(numberOnlyString);
}
}
1995
Java example code below using regex “\D+” which returns the same result.
public class ExtractDigitsFromStringExample2 {
public static void main(String[] args) {
String testString = "My phone number is 123-456-789";
String numberOnlyString = testString.replaceAll("\\D+", "");
System.out.println(numberOnlyString);
}
}
123456789
Java code example that use java.util.regex.Pattern with regex “[^0-9]”
import java.util.regex.Pattern;
public class ExtractDigitsFromStringExample3 {
public static void main(String[] args) {
String testString = "The price of this product is $123";
Pattern notDigitsPattern = Pattern.compile("[^0-9]");
String numberOnlyString = notDigitsPattern.matcher(testString).replaceAll("");
System.out.println(numberOnlyString);
}
}
123
Java code example that use java.util.regex.Pattern with regex “\D+”
import java.util.regex.Pattern;
public class ExtractDigitsFromStringExample4 {
public static void main(String[] args) {
String testString = "Your OTP (one time password) is 485743";
Pattern notDigitsPattern = Pattern.compile("\\D+");
String numberOnlyString = notDigitsPattern.matcher(testString).replaceAll("");
System.out.println(numberOnlyString);
}
}
485743
Happy Coding 😊