I'm trying to remove all non numeric characters from string except for x. I'm a little confused.
my current code
number.replaceAll("[^\\d\\x]", "")
Thanks in advance.
In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.
As you might guess, you can strip all characters but letters and numbers by making a minor change to the replaceAll regular expression, like this: aString. replaceAll("[^a-zA-Z0-9]",""); All I did there was add the numbers [0-9] to our previous range of characters.
use this: [^x0-9]
You may check it on http://gskinner.com/RegExr/
Your regex is
number.replaceAll("[^\\dxX]+", "");
No need to escape normal characters inside a character class. An improvement is also to have the quantifier +
after the character class, that way sequences of those characters are replaced at once and not each char on its own.
Read some regex basics on Xisb: What absolutely every Programmer should know about regular expressions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With