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?
You can make use of the ^ . It considers everything apart from what you have infront of it. String value = string. replaceAll("[^0-9]","");
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 - !
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.
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!
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]
)
string1 = string1.replaceAll("[^0-9]", "");
string2 = string2.replaceAll("[^0-9]", "");
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