当任意模式出现多次时匹配 [英] Matching when an arbitrary pattern appears multiple times

查看:43
本文介绍了当任意模式出现多次时匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

类似的东西,但概括为匹配任何短语,而不仅仅是 foo

Something like this, but generalized to match any phrase, not just 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)

正则表达式可以做到这一点吗?还是我应该使用其他东西?

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

推荐答案

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

You can use this lookahead based regex:

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

正则表达式演示

说明:

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

这篇关于当任意模式出现多次时匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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