Search code examples
javaregexreplaceall

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


Solution

  • 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);