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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/106067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:21:23  来源:igfitidea点击:

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

javaregex

提问by Alex. S.

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!

谢谢!

采纳答案by Pat

In perl

在 perl 中

s/(.)+//g;

Does the trick, I assume if java has perl compatible regexps it should work too.

有什么技巧,我假设如果 java 有 perl 兼容的正则表达式它也应该工作。

Edit: Here is what it means

编辑:这就是它的意思

s {
    (.)  # match any charater ( and capture it )
       # if it is followed by itself 
    +    # One or more times
}{}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+", "");

remember to escape the \1

记得要转义 \1

回答by Jorge Ferreira

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

回答by Matthew Crumley

"14442345".replaceAll("(.)\1+", "");

回答by Jeff Hillman

originalString.replaceAll( "(.)\1+", "" );

回答by Jeff Hillman

in TextEdit (assuming posix expressions) find: [a]+[b]+ replace with: ab

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

回答by Imran

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)

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

(.)+ 

replacement:

更换


回答by jfs

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 tranalog then:

如果 Java 没有tr模拟,那么:

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

Example:

例子:

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

回答by kunwar.sangram

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}");
}