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

时间:2021-11-03 16:59:55

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.

我正在尝试编写一个regex,当任意长度为2或以上的模式在一个短语中出现不止一次时,它将成功。本质上,我想在搜索中使用一个捕获组。

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

类似这样的东西,但概括地匹配任何短语,而不仅仅是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?

regex可以这么做吗?或者我应该用别的东西吗?

1 个解决方案

#1


3  

You can use this lookahead based regex:

您可以使用基于前瞻的regex:

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

RegEx Demo

RegEx演示

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

#1


3  

You can use this lookahead based regex:

您可以使用基于前瞻的regex:

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

RegEx Demo

RegEx演示

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