Search code examples
javaregexregexp-replace

Java replace initial characters in String and preserve length


I'm looking for solution (Java) to replace the initial occurrences of multiple character with the same number of other character, for example if 'a' should be replaced with '-', than I expect:

aaabbaa  -> ---bbaa
aaxxaab  -> --xxaab
xaaaaax  -> xaaaaax

I've tried something like:

"aaabbaa".replaceAll( "^[a]+", "-")        // -bbaa
"aaabbaa".replaceAll( "(?=^[a]+)", "-")    // -aaabbaa

If possible, I prefer regex or oneliner.

Do you have any hints?

regards, Annie


Solution

  • Java supports finite repetition in a lookbehind. You could match a asserting what is on the left from the start of the string are only a's.

    In the replacement using -

    (?<=^a{1,100})a
    

    Regex demo | Java demo

    For example

    System.out.println("aaabbaa".replaceAll("(?<=^a{0,100})a", "-"));
    

    Output

    ---bbaa