37

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?

4 Answers 4

79

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!

Sign up to request clarification or add additional context in comments.

4 Comments

\D would 67% shorter as a pattern. ;)
Yes but far less efficient.
@DaMainBoss how to include negative numbers also? I mean, I have to replace everything that is not a positive/negative number with an empty space. How to do that?
@PankajSinghal negative numbers start with - so something like [^-?0-9] should do the trick. -? there tells the regex engine to match - if it exists(0 or none).
28
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])

Comments

10
string1 = string1.replaceAll("[^0-9]", "");
string2 = string2.replaceAll("[^0-9]", "");

Comments

3

This is the Google Guava #CharMatcher Way.

String alphanumeric = "12ABC34def";

String digits = CharMatcher.JAVA_DIGIT.retainFrom(alphanumeric); // 1234

String letters = CharMatcher.JAVA_LETTER.retainFrom(alphanumeric); // ABCdef

If you only care to match ASCII digits, use

String digits = CharMatcher.inRange('0', '9').retainFrom(alphanumeric); // 1234

If you only care to match letters of the Latin alphabet, use

String letters = CharMatcher.inRange('a', 'z')
                         .or(inRange('A', 'Z')).retainFrom(alphanumeric); // ABCdef

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.