Kev*_*ark 0 java regex regex-lookarounds
我正在尝试以十进制匹配最后一组0.例如:In 9780.56120000 0000匹配.这个正则表达式:
(?<=\.\d{0,20})0*$
似乎在RegexBuddy中工作,但Java失败并出现以下错误:
后视模式匹配必须在索引15附近具有有界最大长度
谁能提供一些有关此问题的见解?
Java正在解释{0,20}为"无界",它不支持.
为什么你需要看看背后?改为使用非捕获组:
(?:\.\d*)0*$
Run Code Online (Sandbox Code Playgroud)
要从String中的十进制数中删除尾随零,请使用以下单行:
input.replaceAll("(\\.(\\d*[1-9])?)0+", "$1");
Run Code Online (Sandbox Code Playgroud)
这是一些测试代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
trim 9780.5612 and 512. but not this00, 00 or 1234000
Run Code Online (Sandbox Code Playgroud)
如果你想处理当只有尾随零也删除小数点,即"512.0000"变为"512",但"123.45000"仍保留小数点即"123.45",执行此操作:
String trimmed = input.replaceAll("(\\.|(\\.(\\d*[1-9])?))0+\\b", "$2");
Run Code Online (Sandbox Code Playgroud)
更多测试代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
trim 9780.5612 and 512 but not this00, 00 or 1234000
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1343 次 |
| 最近记录: |