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

Ale*_* S. 20 java regex

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

之前:aaabbb之后:ab

之前:14442345之后:142345

谢谢!

Pat*_*Pat 36

在perl

s/(.)\1+/$1/g;
Run Code Online (Sandbox Code Playgroud)

诀窍,我假设如果java有perl兼容的regexp它也应该工作.

编辑:这就是它的含义

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)
Run Code Online (Sandbox Code Playgroud)

编辑:正如其他人所指出的,Java中的语法会变成

original.replaceAll("(.)\\1+", "$1");
Run Code Online (Sandbox Code Playgroud)

记得逃避\ 1


Jor*_*ira 17

String a = "aaabbb";
String b = a.replaceAll("(.)\\1+", "$1");
System.out.println("'" + a + "' -> '" + b + "'");
Run Code Online (Sandbox Code Playgroud)