Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurrences of group

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).

like image 596
Alkis Kalogeris Avatar asked May 26 '15 09:05

Alkis Kalogeris


3 Answers

#(?!.*\\.0)

You can try this.Replace by 0.See demo.

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

like image 140
vks Avatar answered Oct 12 '22 23:10

vks


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);
like image 45
Wiktor Stribiżew Avatar answered Oct 12 '22 23:10

Wiktor Stribiżew


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");
like image 2
hexin Avatar answered Oct 12 '22 21:10

hexin