Matching when an arbitrary pattern appears multiple times

依然范特西╮ 提交于 2021-02-05 07:14:25

问题


I'm trying to write a regex that will succeed when an arbitrary pattern of length 2 or greater appears more than once in a phrase. Essentially, I would like to use a capture group in the search.

Something like this, but generalized to match any phrase, not just foo

/foo.*foo/

For example,

Should match:

abcdabcd     ('abcd' is repeated)
foobarfoo    ('foo' is repeated)
mathematics  ('mat' is repeated)

Should not match:

bar        (no repetition of any pattern)
foo        ('o' is repeated but it is not length>=2)

Can regexes do this? Or should I be using something else?


回答1:


You can use this lookahead based regex:

(.{2,})(?=.*?\1)

RegEx Demo

Explanation:

.{2,}     # any 2 or more characters
(.{2,})   # group them into captured group #1
(?=...)   # positive lookahead
(?=.*?\1) # make sure at least one occurrence of captured group #1


来源:https://stackoverflow.com/questions/30239626/matching-when-an-arbitrary-pattern-appears-multiple-times

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!