替换所有出现的组

Replace all occurrences of group

我想替换字符串中出现的所有组。

String test = "###,##.##0.0########";
System.out.println(test);
test = test.replaceAll("\.0(#)", "0");
System.out.println(test);

我想要得到的结果是###,##.##0.000000000 基本上,我想替换 .0 后面的所有 # 符号。 我找到了 this about dynamic replacement,但我真的无法让它发挥作用。

最佳解决方案不会考虑要替换的哈希数(如果这样可以消除任何混淆)。

#(?!.*\.0)

您可以通过 0 尝试 this.Replace。查看演示。

https://regex101.com/r/yW3oJ9/12

您可以将文本拆分为“0.0”并仅替换第二部分:

String[] splited = "###,##.##0.0########".split("0.0");
String finalString = splited[0] + "0.0" + splited[1].replaceAll("#","0");

您可以使用一个简单的正则表达式来完成您的任务。

#(?=#*+$)

(?=#*+$) = 积极 look-ahead that checks for any # that is preceded by 0 or more # symbols before the end of string $. Edit: I am now using a possessive quantifier *+ 以避免任何性能问题。

demo

IDEONE:

String test = "###,##.##0.0###########################################";
test = test.replaceAll("#(?=#*+$)", "0");
System.out.println(test);