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?
[^0-9]only retains one character, you need to add+[^-?]is incorrect. You want-?without any brackets. The?is not a special character when it appears inside the brackets. The brackets mean the digits must be preceded by one character which is neither a hyphen nor a question mark.