简体   繁体   中英

Java Regular Expression removing everything but numbers from String

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.

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]", "");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM