正则表达式将两个(或多个)连续字符替换为一个?


问题内容

在Java中,可以使用哪个正则表达式来替换它们,例如:

之前:aaabbb之后:ab

之前:14442345之后:142345

谢谢!


问题答案:

在Perl中

s/(.)\1+/$1/g;

可以做到这一点,我假设如果Java具有与Perl兼容的正则表达式,它也应该可以工作。

编辑:这是什么意思

s {
    (.)  # match any charater ( and capture it )
    \1   # if it is followed by itself 
    +    # One or more times
}{$1}gx;  # And replace the whole things by the first captured character (with g modifier to replace all occurences)

编辑:正如其他人指出的那样,Java中的语法将成为

original.replaceAll("(.)\\1+", "$1");

记住要逃避\ 1