Ósc*_*pez 490
试试这段代码:
String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");
Run Code Online (Sandbox Code Playgroud)
现在str将包含"12.334.78".
Pet*_*rey 96
我会使用正则表达式.
String text = "-jaskdh2367sd.27askjdfh23";
String digits = text.replaceAll("[^0-9.]", "");
System.out.println(digits);
Run Code Online (Sandbox Code Playgroud)
版画
2367.2723
Run Code Online (Sandbox Code Playgroud)
您可能希望保留-负数.
Faa*_*hir 39
String phoneNumberstr = "Tel: 00971-557890-999";
String numberRefined = phoneNumberstr.replaceAll("[^\\d-]", "");
Run Code Online (Sandbox Code Playgroud)
结果:0097-557890-999
如果你在String中也不需要" - ",你可以这样做:
String phoneNumberstr = "Tel: 00971-55 7890 999";
String numberRefined = phoneNumberstr.replaceAll("[^0-9]", "");
Run Code Online (Sandbox Code Playgroud)
结果:0097557890999
小智 19
用番石榴:
String input = "abx123.5";
String result = CharMatcher.inRange('0', '9').or(CharMatcher.is('.')).retainFrom(input);
Run Code Online (Sandbox Code Playgroud)
请参阅http://code.google.com/p/guava-libraries/wiki/StringsExplained
小智 16
str = str.replaceAll("\\D+","");
Run Code Online (Sandbox Code Playgroud)
货币小数点分隔符可以因区域设置而异。.始终将其视为分隔符可能很危险。IE
??????????????????????????????????????
? Locale ? Sample ?
??????????????????????????????????????
? USA ? $1,222,333.44 USD ?
? United Kingdom ? £1.222.333,44 GBP ?
? European ? €1.333.333,44 EUR ?
??????????????????????????????????????
Run Code Online (Sandbox Code Playgroud)
我认为正确的方法是:
DecimalFormatSymbols通过默认 Locale 或指定之一获取十进制字符。在这里我是如何解决它的:
代码:
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public static String getDigit(String quote, Locale locale) {
char decimalSeparator;
if (locale == null) {
decimalSeparator = new DecimalFormatSymbols().getDecimalSeparator();
} else {
decimalSeparator = new DecimalFormatSymbols(locale).getDecimalSeparator();
}
String regex = "[^0-9" + decimalSeparator + "]";
String valueOnlyDigit = quote.replaceAll(regex, "");
try {
return valueOnlyDigit;
} catch (ArithmeticException | NumberFormatException e) {
Log.e(TAG, "Error in getMoneyAsDecimal", e);
return null;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我希望这会有所帮助,'。
不使用正则表达式的简单方法:
添加点的额外字符检查'.'将解决该要求:
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) || c == '.') {
strBuff.append(c);
}
}
return strBuff.toString();
}
Run Code Online (Sandbox Code Playgroud)
对于来到 Kotlin 的 Android 用户
val dirtyString = " Account Balance: $-12,345.67"
val cleanString = dirtyString.replace("[^\\d.]".toRegex(), "")
Run Code Online (Sandbox Code Playgroud)
输出:
cleanString = "12345.67"
Run Code Online (Sandbox Code Playgroud)
然后可以安全地转换toDouble(),toFloat()或者toInt()如果需要