问题
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