当任意模式出现多次时匹配

时间:2015-05-14 14:14:23

标签: regex

我尝试编写一个正则表达式,当一个长度为2或更大的任意模式在短语中出现多次时,该正则表达式将会成功。基本上,我想在搜索中使用捕获组。

像这样的东西,但推广到匹配任何短语,而不只是foo

/foo.*foo/

例如,

应匹配:

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

不匹配:

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

正则表达式可以这样做吗?或者我应该使用其他东西吗?

1 个答案:

答案 0 :(得分:3)

您可以使用这个基于前瞻性的正则表达式:

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

RegEx Demo

<强>解释

.{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