Java - How to extract only number(int) from String(String)

There are several ways to extract only numbers (int) from a string.

  • Add numbers using regular expressions
  • Add numbers with for statement
  • Add Numbers Using Stream

The easiest way is to use Regex. Let`s look at the methods listed above with examples.

Extract Integer with regular expression

The following code extracts only Integers by regular expression. Pass the regular expression and the string to be converted as arguments to replaceAll().

String str = "aaa1234, ^&*2233pp";
String intStr = str.replaceAll("[^0-9]", "");
System.out.println(intStr);
// output: 12342233

"[^0-9]" means a non-numeric string from 0 to 9.

So, it means change non-numeric characters to spaces ("").

The following code also outputs the same result as above. "^\\d" is an abbreviation of "[^0-9]" and has the same meaning.

String str = "aaa1234, ^&*2233pp";
String intStr = str.replaceAll("[^\\d]", "");
System.out.println(intStr);
// output: 12342233

We recommend that you use this method because it has the shortest code.

If you want to know more about regular expressions, refer to Java - Regular Expression (regex) Example.

Extracting numbers with the for statement

The following code extracts only Integers with the for statement.

String str = "aaa1234, ^&*2233pp";
String intStr = "";
for (int i = 0; i < str.length(); i++) {
    char ch = str.charAt(i);
    if (48 <= ch && ch <= 57) {
        intStr += ch;
    }
}
System.out.println(intStr);
// output: 12342233

48 means 0 in ASCII, 57 means 9 in ASCII. That is, this code extracts only numbers between 0 and 9 from a string.

Extract numbers with Stream

The following code is for extracting a number from a Stream. The for statement and algorithm are the same. Instead of using for, it was processed using Stream.

String str = "aaa1234, ^&*2233pp";
IntStream stream = str.chars();
String intStr = stream.filter((ch)-> (48 <= ch && ch <= 57))
        .mapToObj(ch -> (char)ch)
        .map(Object::toString)
        .collect(Collectors.joining());
System.out.println(intStr);
// output: 12342233
codechachaCopyright ©2019 codechacha