Java Regex - remove non-numeric characters

Viewed 553

I new to Regex and I am trying to remove the non-numeric characters from a string using Java's Regex.

The string could have alphabets after the numbers, and white spaces could appear before the numbers, in between the numbers and alphabets, and after the alphabets.

For example, the a valid string could be " -23 asdf".

I have written the following Regex: "(\\s*)[^-?][^0-9][\\s*a-zA-Z.\\s*]", and I'm using replaceAll method to get rid of non-numeric characters replaceAll(regex, "")

My thought was that \\s* matches zero or more times of the space character
[^-?] retains the optional minus sign
[^0-9] retains the numeric characters
[\\s*a-zA-Z.\\s*] matches white space before and after any alpha characters.\

However, when I try to run this code with input of " -23 asdf", I get an unexpected result of -2

What am I doing wrong?

1 Answers

Here is one viable approach:

String input = "hello world -23 as-df blah blah blah";
String output = input.replaceAll("[^\\d-]|-(?=\\D)", "");
System.out.println(output);

This prints:

-23

The regex used here says to match:

[^\\d-]   any non numeric character EXCEPT for dash (i.e. spare -)
|         OR
-(?=\\D)  remove dash if NOT followed by a number

That is, we do strip off dash if it not be part of a negative number. The replacement is empty string, to remove this unwanted content.

Related