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]+", "0ドルo0ドル");
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?
2 Answers 2
str.replaceAll("[bcdfghjklmnpqrstvwxz]", "0ドルo0ドル");
Remove the + quantifier as it will group consonants.
// when using a greedy quantifier
horse
h | o | rs | e
hoh | o | rsors | e
A plus sign matches one or more of the preceding character, class, or subpattern. For example a+ matches ab and aaab. But unlike a* and a?, the pattern a+ does not match at the beginning of strings that lack an "a" character.
https://autohotkey.com/docs/misc/RegEx-QuickRef.htm
Comments
+ 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/
+is greedy. You should use+?instead.{1}and that seemed to work, and so does+?- are they effectively the same?{1}) is actually useless. You can do without it completely.str = str.replaceAll("([bcdfghjklmnpqrstvwxz])", "1ドルo1ドル");