正则表达式将两个(或者多个)连续字符替换为一个?
时间:2020-03-06 14:28:05 来源:igfitidea点击:
在Java中,可以使用正则表达式替换这些正则表达式,
例如:
前:
aaabbb
后:
b
前:
14442345
后:
142345
谢谢!
解决方案
在Perl中
s/(.)+//g;
可以做到这一点,我假设如果Java具有与Perl兼容的正则表达式,它也应该可以工作。
编辑:这是什么意思
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)
编辑:正如其他人指出的那样,Java中的语法将成为
original.replaceAll("(.)\1+", "");
记住要逃避\ 1
String a = "aaabbb"; String b = a.replaceAll("(.)\1+", ""); System.out.println("'" + a + "' -> '" + b + "'");
"14442345".replaceAll("(.)\1+", "");
originalString.replaceAll( "(.)\1+", "" );
在TextEdit中(假设posix表达式)
找到:[a] + [b] +
替换为:ab
匹配模式(在Java /语言中,必须转义):
(.)\1+
或者(在可以使用不将\当作转义符的字符串的语言中)
(.)+
替换:
在Perl中:
tr/a-z0-9//s;
例子:
$ perl -E'@a = (aaabbb, 14442345); for(@a) { tr/a-z0-9//s; say }' ab 142345
如果Java没有tr
类似物,则:
s/(.)+//sg; #NOTE: `s` modifier. It takes into account consecutive newlines.
例子:
$ perl -E'@a = (aaabbb, 14442345); for(@a) { s/(.)+//sg; say }' ab 142345