36

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?

Dominik
  • 4,588
  • 13
  • 41
  • 57

4 Answers4

75

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!

DaMainBoss
  • 1,985
  • 1
  • 18
  • 25
27
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])

David Chouinard
  • 5,676
  • 8
  • 41
  • 60
om-nom-nom
  • 61,565
  • 12
  • 180
  • 225
10
string1 = string1.replaceAll("[^0-9]", "");
string2 = string2.replaceAll("[^0-9]", "");
JK.
  • 5,086
  • 1
  • 26
  • 26
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
Kerem Baydoğan
  • 10,172
  • 1
  • 40
  • 49