Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regular Expression removing everything but numbers from String

Tags:

java

regex

I have two strings string1 = 44.365 Online order and string2 = 0 Request Delivery. Now I would like to apply a regular expression to these strings that filters out everything but numbers so I get integers like string1 = 44365 and string2 = 0.

How can I accomplish this?

like image 775
Dominik Avatar asked Jul 30 '11 13:07

Dominik


People also ask

How do you remove all except numbers in a string in Java?

You can make use of the ^ . It considers everything apart from what you have infront of it. String value = string. replaceAll("[^0-9]","");

How do you remove all but letters from a string in Java?

You can use a regular expression and replaceAll() method of java. lang. String class to remove all special characters from String. A special character is nothing but characters like - !

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.


3 Answers

You can make use of the ^. It considers everything apart from what you have infront of it.

So if you have [^y] its going to filter everything apart from y. In your case you would do something like

String value = string.replaceAll("[^0-9]","");

where string is a variable holding the actual text!

like image 181
DaMainBoss Avatar answered Sep 23 '22 17:09

DaMainBoss


String clean1 = string1.replaceAll("[^0-9]", "");

or

String clean2 = string2.replaceAll("[^\\d]", "");

Where \d is a shortcut to [0-9] character class, or

String clean3 = string1.replaceAll("\\D", "");

Where \D is a negation of the \d class (which means [^0-9])

like image 28
om-nom-nom Avatar answered Sep 19 '22 17:09

om-nom-nom


string1 = string1.replaceAll("[^0-9]", "");
string2 = string2.replaceAll("[^0-9]", "");
like image 10
JK. Avatar answered Sep 23 '22 17:09

JK.