[java] How do I remove the non-numeric character from a string in java?

I have a long string. What is the regular expression to split the numbers into the array?

This question is related to java regex

The answer is


Another regex solution:

string.replace(/\D/g,'');  //remove the non-Numeric

Similarly, you can

string.replace(/\W/g,'');  //remove the non-alphaNumeric

In RegEX, the symbol '\' would make the letter following it a template: \w -- alphanumeric, and \W - Non-AlphaNumeric, negates when you capitalize the letter.


You will want to use the String class' Split() method and pass in a regular expression of "\D+" which will match at least one non-number.

myString.split("\\D+");

Java 8 collection streams :

StringBuilder sb = new StringBuilder();
test.chars().mapToObj(i -> (char) i).filter(Character::isDigit).forEach(sb::append);
System.out.println(sb.toString());

One more approach for removing all non-numeric characters from a string:

String newString = oldString.replaceAll("[^0-9]", "");

Simple way without using Regex:

public static String getOnlyNumerics(String str) {
    if (str == null) {
        return null;
    }
    StringBuffer strBuff = new StringBuffer();
    char c;
    for (int i = 0; i < str.length() ; i++) {
        c = str.charAt(i);
        if (Character.isDigit(c)) {
            strBuff.append(c);
        }
    }
    return strBuff.toString();
}

Are you removing or splitting? This will remove all the non-numeric characters.

myStr = myStr.replaceAll( "[^\\d]", "" )

you could use a recursive method like below:

public static String getAllNumbersFromString(String input) {
        if (input == null || input.length() == 0) {
            return "";
        }
        char c = input.charAt(input.length() - 1);
        String newinput = input.substring(0, input.length() - 1);

            if (c >= '0' && c<= '9') {
            return getAllNumbersFromString(newinput) + c;

        } else {
            return getAllNumbersFromString(newinput);
        }
    } 

Previous answers will strip your decimal point. If you want to save your decimal, you might want to

String str = "My values are : 900.00, 700.00, 650.50";

String[] values = str.split("[^\\d.?\\d]"); 
// split on wherever they are not digits except the '.' decimal point
// values: { "900.00", "700.00", "650.50"}  

This works in Flex SDK 4.14.0

myString.replace(/[^0-9&&^.]/g, "");


String str= "somestring";
String[] values = str.split("\\D+");