Search code examples
javaregexreplaceall

String.replaceAll() with regex gets messed up


I'm trying to implement the Swedish "Robbers language" in Java. It's basically just replacing each consonant with itself, followed by a "o", followed by itself again. I thought I had it working with this code

str.replaceAll("[bcdfghjklmnpqrstvwxz]+", "$0o$0");

but it fails when there are two or more subsequent consonants, for example

String str = "horse";

It should produce hohororsose, but instead I get hohorsorse. I'm guessing the replacement somehow messes up the matching indexes in the original string. How can I make it work?


Solution

  • + means: Between one and unlimited times, as many times as possible, giving back as needed (greedy)

    +? means: Between one and unlimited times, as few times as possible, expanding as needed (lazy)

    {1} means: Exactly 1 time (meaningless quantifier)

    In your case you don't need a quantifier.

    You can experiment with regular expressions online at https://regex101.com/