String.replaceAll() 与正则表达式搞砸了

String.replaceAll() with regex gets messed up

我正在尝试在 Java 中实现 Swedish "Robbers language"。它基本上只是用自己替换每个辅音,然后是 "o",然后再次是自己。我以为我可以使用此代码

str.replaceAll("[bcdfghjklmnpqrstvwxz]+", "[=11=]o[=11=]");

但当后面有两个或多个辅音时会失败,例如

String str = "horse";

它应该产生 hohororsose,但我却得到 hohorsorse。我猜替换以某种方式弄乱了原始字符串中的匹配索引。我怎样才能让它发挥作用?

str.replaceAll("[bcdfghjklmnpqrstvwxz]", "[=10=]o[=10=]");

删除 + 量词,因为它将对辅音进行分组。

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

+意思是:一次到无限次之间,尽可能多次,按需回馈(贪心)

+?意思是:一次到无限次之间,次数越少越好,按需扩充(偷懒)

{1}表示:恰好1次(无意义量词)

在你的情况下你不需要量词。

您可以在 https://regex101.com/

在线试验正则表达式