Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java remove non numeric characters from string except x

Tags:

java

regex

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.

like image 362
Code Junkie Avatar asked May 22 '12 18:05

Code Junkie


People also ask

How do I remove non-numeric characters from a string?

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.

How do you replace all characters except numbers in Java?

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.


2 Answers

use this: [^x0-9]

You may check it on http://gskinner.com/RegExr/

like image 198
Nurlan Avatar answered Oct 12 '22 20:10

Nurlan


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

like image 40
stema Avatar answered Oct 12 '22 20:10

stema