Java replace initial characters in String and preserve length

Viewed 384

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

3 Answers

If using Java 9+, use the lambda overload for replaceAll:

import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String res = Pattern
            .compile("^a+")
            .matcher("aaabbb")
            .replaceAll(m -> "-".repeat(m.group().length()));
        System.out.println(res); // => ---bbb
    }
}

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

Use a char[]:

char[] cs = str.toCharArray();
for (int i = 0; i < cs.length && cs[i] == 'a'; ++i) {
  cs[i] = '-';
}
String newStr = new String(cs);
Related