开发者

Java Regular Expression removing everything but numbers from String

开发者 https://www.devze.com 2023-03-24 14:49 出处:网络
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 st开发者_开发知识库rings that filters out everything but numb

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 st开发者_开发知识库rings 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
0

精彩评论

暂无评论...
验证码 换一张
取 消