试图删除所有不是0-9和句号的字母和字符。我使用的是character。isdigit()但它也删除了小数,我怎么能保留小数呢?


当前回答

str = str.replaceAll("\\D+","");

其他回答

用java 8流替换它的方法:

public static void main(String[] args) throws IOException
{
    String test = "ab19198zxncvl1308j10923.";
    StringBuilder result = new StringBuilder();

    test.chars().mapToObj( i-> (char)i ).filter( c -> Character.isDigit(c) || c == '.' ).forEach( c -> result.append(c) );

    System.out.println( result ); //returns 19198.130810923.
}

试试下面的代码:

String str = "a12.334tyz.78x";
str = str.replaceAll("[^\\d.]", "");

现在str将包含“12.334.78”。

不使用Regex的简单方法:

为点'添加额外的字符检查。'将解决需求:

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();
}

它处理空输入,负数和小数(你需要在你的项目中包含Apache Commons Lang库,版本3.8或更高):

import org.apache.commons.lang3.RegExUtils;
result = RegExUtils.removeAll(input, "-?[^\\d.]");

图书馆参考资料:https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RegExUtils.html

我会用正则表达式。

String text = "-jaskdh2367sd.27askjdfh23";
String digits = text.replaceAll("[^0-9.]", "");
System.out.println(digits);

打印

2367.2723

你也可以用-来表示负数。