java 使用android从字母数字字符串中提取数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10734989/
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 numbers from an alpha numeric string using android
提问by Prasanth_AndroidJD
I have to extract only numeric values from String str="sdfvsdf68fsdfsf8999fsdf09"
.
How can I extract numbers from an alpha numeric string in android?
我必须只从String str="sdfvsdf68fsdfsf8999fsdf09"
. 如何从android中的字母数字字符串中提取数字?
回答by Mohammed Azharuddin Shaikh
String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");
update:
更新:
String str="fgdfg12°59'50\" Nfr | gdfg: 80°15'25\" Efgd";
String[] spitStr= str.split("\|");
String numberOne= spitStr[0].replaceAll("[^0-9]", "");
String numberSecond= spitStr[1].replaceAll("[^0-9]", "");
回答by Vinay Kumar Baghel
public static String getOnlyNumerics(String str) {
if (str == null) {
return null;
}
StringBuffer strBuff = new StringBuffer();
char c;
for (int i = 0; i < str.length() ; i++) {
c = str.charAt(i);
if (Character.isDigit(c)) {
strBuff.append(c);
}
}
return strBuff.toString();
}
回答by Sean Das
public static int extractNumberFromAnyAlphaNumeric(String alphaNumeric) {
alphaNumeric = alphaNumeric.length() > 0 ? alphaNumeric.replaceAll("\D+", "") : "";
int num = alphaNumeric.length() > 0 ? Integer.parseInt(alphaNumeric) : 0; // or -1
return num;
}
You can set the value to 0 or -1 (what to do if no number is found in the alphanumeric at all) as per your needs
您可以根据需要将该值设置为 0 或 -1(如果在字母数字中根本找不到数字该怎么办)