您的正则表达式
([a-z])\1{2,}匹配并将ASCII字母捕获到组1中,然后匹配两次或多次出现该值。因此,您需要替换为$1包含捕获的值的后向引用。如果使用一个
$1,
aaaaa则将替换为一个
a,如果使用
$1$1,则将替换为
aa。
String twoConsecutivesOnly = data.replaceAll(regex, "$1$1");String noTwoConsecutives = data.replaceAll(regex, "$1");
请参阅Java演示。
如果需要使正则表达式不区分大小写,请使用
"(?i)([a-z])\1{2,}"甚至
"(\p{Alpha})\1{2,}"。如果必须处理任何Unipre字母,请使用"(\p{L})\1{2,}"。奖励 :在一般情况下,要替换任意数量的重复使用的连续字符
text = text.replaceAll("(?s)(.)\1+", "$1"); // any charstext = text.replaceAll("(.)\1+", "$1"); // any chars but line breakstext = text.replaceAll("(\p{L})\1+", "$1"); // any letterstext = text.replaceAll("(\w)\1+", "$1"); // any ASCII alnum + _ chars


