I want to replace all the occurrences of a group in a string.
String test = "###,##.##0.0########";
System.out.println(test);
test = test.replaceAll("\\.0(#)", "0");
System.out.println(test);
The result I am trying to obtain is ###,##.##0.000000000
Basically, I want to replace all #
symbols that are trailing the .0
.
I've found this about dynamic replacement but I can't really make it work.
The optimal solution will not take into account the number of hashes to be replaced (if that clears any confusion).
#(?!.*\\.0)
You can try this.Replace by 0
.See demo.
https://regex101.com/r/yW3oJ9/12
You can use a simple regex to achieve your task.
#(?=#*+$)
(?=#*+$)
= A positive 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 *+
to avoid any performance issues.
See demo
IDEONE:
String test = "###,##.##0.0###########################################";
test = test.replaceAll("#(?=#*+$)", "0");
System.out.println(test);
You can split your text on "0.0" and replace just for the second part:
String[] splited = "###,##.##0.0########".split("0.0");
String finalString = splited[0] + "0.0" + splited[1].replaceAll("#","0");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With