1

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?

asked Mar 16, 2016 at 20:16
5
  • + is greedy. You should use +? instead. Commented Mar 16, 2016 at 20:24
  • I just realized the problem was the pattern, don't know how I could miss that! I just tried using {1} and that seemed to work, and so does +? - are they effectively the same? Commented Mar 16, 2016 at 20:26
  • No. But the quantifier ({1}) is actually useless. You can do without it completely. Commented Mar 16, 2016 at 20:28
  • str = str.replaceAll("([bcdfghjklmnpqrstvwxz])", "1ドルo1ドル"); Commented Mar 16, 2016 at 20:29
  • Ok, totacockok :) If you care to make it an answer I'll accept it. Commented Mar 16, 2016 at 20:30

2 Answers 2

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

answered Mar 16, 2016 at 20:31
Sign up to request clarification or add additional context in comments.

Comments

1

+ 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/

answered Mar 16, 2016 at 20:34

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.