哪些正则表达式可以匹配相同字符的序列? [英] What regex can match sequences of the same character?

查看:80
本文介绍了哪些正则表达式可以匹配相同字符的序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个朋友问我这个,我很沮丧:是否有一种方法可以制作与相同字符序列匹配的正则表达式?例如,匹配"aaa","bbb",而不匹配"abc"?

A friend asked me this and I was stumped: Is there a way to craft a regular expression that matches a sequence of the same character? E.g., match on 'aaa', 'bbb', but not 'abc'?

m|\w{2,3}| 

不会成功,因为它会匹配'abc'.

Wouldn't do the trick as it would match 'abc'.

m|a{2,3}| 

不会成功,因为它与'bbb','ccc'等不匹配.

Wouldn't do the trick as it wouldn't match 'bbb', 'ccc', etc.

推荐答案

当然!分组和引用是您的朋友:

Sure thing! Grouping and references are your friends:

(.)\1+

将匹配2个或更多相同字符的事件.仅对于单词构成字符,使用\w而不是.,即:

Will match 2 or more occurences of the same character. For word constituent characters only, use \w instead of ., i.e.:

(\w)\1+

这篇关于哪些正则表达式可以匹配相同字符的序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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