从Java中的字符串中提取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4030928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extract digits from a string in Java
提问by user488469
I have a Java String
object. I need to extract only digits from it. I'll give an example:
我有一个 JavaString
对象。我只需要从中提取数字。我举个例子:
"123-456-789"
I want "123456789"
"123-456-789"
我想要 "123456789"
Is there a library function that extracts only digits?
是否有仅提取数字的库函数?
Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?
感谢您的回答。在尝试这些之前,我需要知道是否必须安装任何其他库?
采纳答案by codaddict
You can use regex and delete non-digits.
您可以使用正则表达式并删除非数字。
str = str.replaceAll("\D+","");
回答by dogbane
public String extractDigits(String src) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}
回答by Sean Patrick Floyd
Here's a more verbose solution. Less elegant, but probably faster:
这是一个更详细的解决方案。不太优雅,但可能更快:
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();
}
Test Code:
测试代码:
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);
}
Output:
输出:
0123456789
0123456789
BTW: I did not use Character.isDigit(ch)because it accepts many other chars except 0 - 9.
顺便说一句:我没有使用Character.isDigit(ch)因为它接受除 0 - 9 之外的许多其他字符。
回答by BjornS
Using Google Guava:
使用谷歌番石榴:
CharMatcher.DIGIT.retainFrom("123-456-789");
CharMatcher is plug-able and quite interesting to use, for instance you can do the following:
CharMatcher 是可插入的并且使用起来非常有趣,例如您可以执行以下操作:
String input = "My phone number is 123-456-789!";
String output = CharMatcher.is('-').or(CharMatcher.DIGIT).retainFrom(input);
output == 123-456-789
输出 == 123-456-789
回答by Emil
Using Google Guava:
使用谷歌番石榴:
CharMatcher.inRange('0','9').retainFrom("123-456-789")
UPDATE:
更新:
Using Precomputed CharMatchercan further improve performance
使用Precomputed CharMatcher可以进一步提高性能
CharMatcher ASCII_DIGITS=CharMatcher.inRange('0','9').precomputed();
ASCII_DIGITS.retainFrom("123-456-789");
回答by Raghunandan
Use regular expression to match your requirement.
使用正则表达式来匹配您的要求。
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);
}
回答by user3679646
input.replaceAll("[^0-9?!\.]","")
This will ignore the decimal points.
这将忽略小数点。
eg: if you have an input as 445.3kg
the output will be 445.3
.
例如:如果你有一个输入,445.3kg
输出将是445.3
.
回答by Perlos
I inspired by code Sean Patrick Floyd and little rewrite it for maximum performance i get.
我受到代码 Sean Patrick Floyd 的启发,并且很少重写它以获得最大的性能。
public static String stripNonDigitsV2( CharSequence input ) {
if (input == null)
return null;
if ( input.length() == 0 )
return "";
char[] result = new char[input.length()];
int cursor = 0;
CharBuffer buffer = CharBuffer.wrap( input );
while ( buffer.hasRemaining() ) {
char chr = buffer.get();
if ( chr > 47 && chr < 58 )
result[cursor++] = chr;
}
return new String( result, 0, cursor );
}
i do Performance testto very long String with minimal numbers and result is:
我用最少的数字对很长的字符串进行性能测试,结果是:
- Original code is 25,5% slower
- Guava approach is 2.5-3 times slower
- Regular expression with D+ is 3-3.5 times slower
- Regular expression with only D is 25+ times slower
- 原始代码慢 25.5%
- Guava 方法慢 2.5-3 倍
- 使用 D+ 的正则表达式慢 3-3.5 倍
- 只有 D 的正则表达式慢 25 倍以上
Btw it depends on how long that string is. With string that contains only 6 number is guava 50% slower and regexp 1 times slower
顺便说一句,这取决于该字符串的长度。仅包含 6 个数字的字符串是番石榴慢 50%,正则表达式慢 1 倍
回答by sendon1982
You can use str.replaceAll("[^0-9]", "");
您可以使用 str.replaceAll("[^0-9]", "");
回答by Kairat Koibagarov
I have finalized the code for phone numbers +9 (987) 124124.
我已经完成了电话号码 +9 (987) 124124 的代码。
Unicode characters occupy 4 bytes.
Unicode 字符占 4 个字节。
public static String stripNonDigitsV2( CharSequence input ) {
if (input == null)
return null;
if ( input.length() == 0 )
return "";
char[] result = new char[input.length()];
int cursor = 0;
CharBuffer buffer = CharBuffer.wrap( input );
int i=0;
while ( i< buffer.length() ) { //buffer.hasRemaining()
char chr = buffer.get(i);
if (chr=='u'){
i=i+5;
chr=buffer.get(i);
}
if ( chr > 39 && chr < 58 )
result[cursor++] = chr;
i=i+1;
}
return new String( result, 0, cursor );
}