我有一个Java字符串对象。我只需要从中提取数字。我举个例子:
123456-789我要123456789
是否存在只提取数字的库函数?
谢谢你的回答。在我尝试这些之前,我需要知道我是否必须安装任何额外的llibraries?
我有一个Java字符串对象。我只需要从中提取数字。我举个例子:
123456-789我要123456789
是否存在只提取数字的库函数?
谢谢你的回答。在我尝试这些之前,我需要知道我是否必须安装任何额外的llibraries?
当前回答
使用正则表达式来匹配您的需求。
String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();
System.out.print(num);
}
其他回答
使用谷歌番石榴:
CharMatcher.inRange('0','9').retainFrom("123-456-789")
更新:
使用Precomputed CharMatcher可以进一步提高性能
CharMatcher ASCII_DIGITS=CharMatcher.inRange('0','9').precomputed();
ASCII_DIGITS.retainFrom("123-456-789");
代码:
public class saasa {
public static void main(String[] args) {
// TODO Auto-generated method stub
String t="123-456-789";
t=t.replaceAll("-", "");
System.out.println(t);
}
这里有一个更详细的解决方案。不那么优雅,但可能更快:
public static String stripNonDigits(
final CharSequence input /* inspired by seh's comment */){
final StringBuilder sb = new StringBuilder(
input.length() /* also inspired by seh's comment */);
for(int i = 0; i < input.length(); i++){
final char c = input.charAt(i);
if(c > 47 && c < 58){
sb.append(c);
}
}
return sb.toString();
}
测试代码:
public static void main(final String[] args){
final String input = "0-123-abc-456-xyz-789";
final String result = stripNonDigits(input);
System.out.println(result);
}
输出:
0123456789
顺便说一句:我没有使用Character.isDigit(ch),因为它接受许多其他字符,除了0 - 9。
input.replaceAll("[^0-9?!\\.]","")
这将忽略小数点。
例如:如果你有一个445.3公斤的输入,输出将是445.3公斤。
你可以使用str.replaceAll("[^0-9]", "");