正则表达式替换重复的字符 [英] Regex to replace repeated characters
本文介绍了正则表达式替换重复的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人可以给我一个Java正则表达式来替换以下内容吗。
Can someone give me a Java regex to replace the following.
如果我有这样的单词Cooooool,我需要将其转换为Coool 3点钟。所以我可以用正常的单词酷来区分它。
If I have a word like this "Cooooool", I need to convert this to "Coool" with 3 o's. So that I can distinguish it with the normal word "cool".
另一个例子:happyyyyyy应该是happyyy
Another ex: "happyyyyyy" should be "happyyy"
replaceAll("(.)\\1+","$1"))
我尝试了这个,但它删除了所有重复的字符,只剩下一个。
I tried this but it removes all the repeating characters leaving only one.
推荐答案
改变你的正则表达式如下。
Change your regex like below.
string.replaceAll("((.)\\2{2})\\2+","$1");
-
(
第一个caturing组的开始。 -
(。)
捕获任何字符。对于这种情况,你可以使用[az]
-
\\2
指第二个捕获组。\\2 {2}
必须重复两次。 -
)
第一个捕获组结束。所以这将捕获前三个重复字符。 -
\\2 +
重复第二组一次或多次。 (
start of the first caturing group.(.)
captures any character. For this case, you may use[a-z]
\\2
refers the second capturing group.\\2{2}
which must be repeated exactly two times.)
End of first capturing group. So this would capture the first three repeating characters.\\2+
repeats the second group one or more times.
这篇关于正则表达式替换重复的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文