Extract Numbers from String – Java

Java code to extract digits or numbers from a string with logic and explanation. We’ll use 2 methods: (1) using regex expression with replaceAll method of String object, and (2) using loop and ascii values of characters.

Extract Numbers from String using regex


Use the regular expression [^0-9] to find non-integer characters in the string and replace them with an empty value using the method replaceAll.

Java Code:

public class Sample {

	public static void main(String[] args) {

		String str = "XXXX1234G21";

		String digits = str.replaceAll("[^0-9]", "");


Output: 123421


The String method “String replaceAll(String regex, String replacement)” finds the characters or patterns in the given string using the regex expression provided by you and replaces them with the option that you provide.

In the given program, the regex [^0-9] matches any single character that is not a number, and the method replaces those characters with an empty value specified by “”.


The regular expression replaceAll(“\\D+”, “”); will also work to extract numbers or digits.

You can read more on the regular expression on the wiki here.

Extract Numbers from String using loop and ascii value


Go over all the characters in the string using a loop, get the ascii code for each character. Check if the ascii code is between 48 and 57 (ascii for 0 is 48, for 1 is 49 ……and 9 is 57). If ascii comes between the range 48 and 47, then construct the numbers. You can store into a string value e.g. numString in the given code below. Finally convert that number string to an integer value. That’s it.


public class Sample {

	public static void main(String[] args) {

		String str = "XXXX1234G21#";

		String numString = "";

		for (int i = 0; i < str.length(); i++) {
			int ascii = str.charAt(i);

			// ascii value of 0 is 48 and of 9 is 57
			if (ascii >= 48 && ascii <= (57)) {
				numString += (char) ascii;
		// Convert number in string form to
		//an integer value
		int numbers = Integer.parseInt(numString);




Using a for loop the given string is iterated up to the string length.  The charAt(i) method returns character at given index but if you store into an integer variable it will be the ascii value of that character.

Check if the ascii value is in the range 48 and 57, then construct the integers in form of a string. This would be the string of all integers separated.

Convert the integer string into a number. That will result the output.

Uses of Extracting Numbers from String:

Here is a scenario in real-time where you may need to extract numbers from strings.


Suppose you have a text file containing millions of user’s names and their phone numbers. And,

you want to send SMS to all the users via an application. The application can read the content of the file and extract the phone number and send the SMS to all.

Leave a Comment