从字符串格式的十进制/Java 错误中删除尾随 0 - 后视模式匹配必须在索引 15 附近具有有界的最大长度



我正在尝试匹配小数中的最后一组 0。例如:在9780.56120000 0000中会匹配。此正则表达式:

(?<=.d{0,20})0*$

似乎在正则表达式好友中工作,但 Java 失败并出现以下错误:

后视模式匹配必须具有接近的有界最大长度 索引 15

任何人都可以对这个问题提供一些见解吗?

Java将{0,20}解释为"无界",但它不支持。

为什么需要看后面?请改用非捕获组:

(?:.d*)0*$

编辑:

若要从字符串中的十进制数字中删除尾随零,请使用以下单行:

input.replaceAll("(\.(\d*[1-9])?)0+", "$1");

下面是一些测试代码:

public static void main(String[] args) {
    String input = "trim 9780.56120000 and 512.0000 but not this00, 00 or 1234000";
    String trimmed = input.replaceAll("(\.(\d*[1-9])?)0+", "$1");
    System.out.println(trimmed);
}

输出:

trim 9780.5612 and 512. but not this00, 00 or 1234000

再次编辑:

如果要处理只有尾随零时也删除小数点,即"512.0000"变为"512",但"123.45000"仍保留小数点即"123.45",请执行以下操作:

String trimmed = input.replaceAll("(\.|(\.(\d*[1-9])?))0+\b", "$2");

更多测试代码:

public static void main(String[] args) {
    String input = "trim 9780.56120000 and 512.0000 but not this00, 00 or 1234000";
    String trimmed = input.replaceAll("(\.|(\.(\d*[1-9])?))0+\b", "$2");
    System.out.println(trimmed);
}

输出:

trim 9780.5612 and 512 but not this00, 00 or 1234000

我最终根本不使用正则表达式,并决定从末尾开始向后循环小数的每个字符。这是我使用的实现。感谢波西米亚人把我推向正确的方向。

if(num.contains(".")) { // If it's a decimal
    int i = num.length() - 1;
    while(i > 0 && num.charAt(i) == '0') {
        i--;
    }
    num = num.substring(0, i + 1);
}

基于此处的rtrim函数的代码:http://www.fromdev.com/2009/07/playing-with-java-string-trim-basics.html

编辑:这里有一些东西可以删除此解决方案的小数点。

// Remove the decimal if we don't need it anymore
// Eg: 4.0000 -> 4. -> 4
if(num.substring(num.length() - 1).equals(".")) {
        num = num.substring(0, num.length() - 1);
}

最新更新