正则表达式只用一个替换两个(或多个)连续字符? [英] regular expression to replace two (or more) consecutive characters by only one?

查看:142
本文介绍了正则表达式只用一个替换两个(或多个)连续字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In java, which regular expression can be used to replace these, for example:

之前:
aaabbb
之后:
ab

before: aaabbb after: ab

之前:
14442345
之后:
142345

before: 14442345 after: 142345

谢谢!

推荐答案

在perl

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

诀窍,我认为如果java具有perl兼容的regexp它也应该工作。

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

编辑:这就是它的含义

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中的语法将变为

As others have pointed out, the syntax in Java would become

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

记得逃避\1

这篇关于正则表达式只用一个替换两个(或多个)连续字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆