简体   繁体   中英

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

#(?!.*\\.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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM