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?

Dominik
  • 4,718
  • 13
  • 44
  • 58

4 Answers4

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!

DaMainBoss
  • 2,035
  • 1
  • 19
  • 26
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])

David Chouinard
  • 6,466
  • 8
  • 43
  • 61
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
10
string1 = string1.replaceAll("[^0-9]", "");
string2 = string2.replaceAll("[^0-9]", "");
JK.
  • 5,126
  • 1
  • 27
  • 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,475
  • 1
  • 43
  • 50