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

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

之前:aaabbb之后:ab

之前:14442345之后:142345

谢谢!

在perl

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

诀窍,我假设如果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) 

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

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

记得逃避\ 1

 String a = "aaabbb"; String b = a.replaceAll("(.)\\1+", "$1"); System.out.println("'" + a + "' -> '" + b + "'"); 
 "14442345".replaceAll("(.)\\1+", "$1"); 
 originalString.replaceAll( "(.)\\1+", "$1" ); 

匹配模式 (在Java /必须转义\的语言中):

 (.)\\1+ 

或(在您可以使用不将\视为\作为转义字符的字符串的语言中)

 (.)\1+ 

替换

 $1 

在TextEdit中(假设posix表达式)find:[a] + [b] +替换为:ab

在Perl中:

 tr/a-z0-9//s; 

例:

 $ perl -E'@a = (aaabbb, 14442345); for(@a) { tr/a-z0-9//s; say }' ab 142345 

如果Java没有tr模拟那么:

 s/(.)\1+/$1/sg; #NOTE: `s` modifier. It takes into account consecutive newlines. 

例:

 $ perl -E'@a = (aaabbb, 14442345); for(@a) { s/(.)\1+/$1/sg; say }' ab 142345 

添加了Java 7:命名组

 static String cleanDuplicates(@NonNull final String val) { assert val != null; return val.replaceAll("(?.)\\k+","${dup}"); }