简体   繁体   English

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

[英]regular expression to replace two (or more) consecutive characters by only one?

In java, which regular expression can be used to replace these, for example: 在java中,可以使用哪个正则表达式来替换它们,例如:

before: aaabbb after: ab 之前:aaabbb之后:ab

before: 14442345 after: 142345 之前:14442345之后:142345

thanks! 谢谢!

In perl 在perl

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

Does the trick, I assume if java has perl compatible regexps it should work too. 诀窍,我假设如果java有perl兼容的regexp它也应该工作。

Edit: Here is what it means 编辑:这就是它的含义

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)

Edit: As others have pointed out, the syntax in Java would become 编辑:正如其他人所指出的,Java中的语法会变成

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

remember to escape the \\1 记得逃避\\ 1

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

match pattern (in Java/languages where \\ must be escaped): 匹配模式 (在Java /必须转义\\的语言中):

(.)\\1+

or (in languages where you can use strings which don't treat \\ as escape character) 或(在您可以使用不将\\视为\\作为转义字符的字符串的语言中)

(.)\1+ 

replacement : 替换

$1

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

In Perl: 在Perl中:

tr/a-z0-9//s;

Example: 例:

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

If Java has no tr analog then: 如果Java没有tr模拟那么:

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

Example: 例:

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

Sugared with a Java 7 : Named Groups 添加了Java 7:命名组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM