Java 正则表达式匹配两个连续字符,除非后面/前面有更多相同字符
我有一个字符串,看起来像这样:Java 正则表达式匹配两个连续字符,除非后面/前面有更多相同字符,java,regex,Java,Regex,我有一个字符串,看起来像这样:qqq-Eqq-Eqq-Eqq-Fq。我想用h替换有两个连续字符的所有序列(在本例中为qq),所需的输出如下所示:qqq Eh eqq Ch Eh Fq 但是,我不希望正则表达式匹配两个以上q的序列(qqq或qqq),并使字符串看起来像这样:hq Eh Ehq Ch Eh Fq。我尝试了下面的方法,但结果是我不想要的输出 text = "qqq Eqq Eqqq Cqq Eqq Fq"; text = text.replaceAll("[q]{2}", "h");
qqq-Eqq-Eqq-Eqq-Fq
。我想用h
替换有两个连续字符的所有序列(在本例中为qq
),所需的输出如下所示:qqq Eh eqq Ch Eh Fq
但是,我不希望正则表达式匹配两个以上q的序列(qqq
或qqq
),并使字符串看起来像这样:hq Eh Ehq Ch Eh Fq
。我尝试了下面的方法,但结果是我不想要的输出
text = "qqq Eqq Eqqq Cqq Eqq Fq";
text = text.replaceAll("[q]{2}", "h");
我也尝试过只替换
q
,后面跟一个空白字符,但这只会匹配每个单词中最后两个q
。有没有办法替换两个连续的字符,除非它们后面跟有同一字符的第三个或第四个?如果有帮助的话,语言是Java。您可以使用基于查找的正则表达式:
String text = "qqq Eqq Eqqq Cqq Eqq Fq";
text = text.replaceAll("(?<!q)q{2}", "h");
System.out.println(text);
// => hq Eh Ehq Ch Eh Fq
String text=“qqq Eqq Eqq Cqq Eqq Fq”;
text=text.replaceAll(“(?如果你想匹配任何字符,而不是特定的字符,你必须使用一些非常复杂的东西,因为Java的正则表达式不支持可变长度look-behind
s。我想到了这个:
(?!([a-z])\1\1)(.)([a-z])\3(?!\3)
说明:
(?! # negative look-ahead
([a-z])\1\1 # [group 1] match a letter and 2 more of the same letter
) # end of the negative look-ahead
(.) # [group 2] match any character - this is for some other character
# before what you want ('E', 'C', or 'F' in your examples)
# this will not match the repeated character -
# guaranteed by the previous negative look-ahead
([a-z]) # [group 3] the letter to be replaced
\3 # the same letter (reference to the previous group)
(?!\3) # negative look-ahead -
# makes the pattern not match more than 2 of the same character
您必须替换为$2h
($2
在模式中是(。
)
,