正则表达式匹配同一模式的多次出现

Max*_*Max 7 regex

我正在尝试运行一个测试,看看具有多行的长字符串是否多次出现相同的模式,或者假设出现 5 或 10 次。

所以像这样的字符串:

$string = "this is a test pattern1 more of a test pattern1

and so on and so on pattern1";
Run Code Online (Sandbox Code Playgroud)

所以在这种情况下我尝试使用 PHP:

if (preg_match('/(pattern1)\1{2,}/m',$string)) print "Found 2+ occurrences of pattern1\n";
Run Code Online (Sandbox Code Playgroud)

当然这是行不通的。

而且我不能使用preg_match_all.

有人可以纠正我的正则表达式吗?

Cas*_*yte 3

如果我理解得很好,那么您离好的模式就不远了(这里出现了三次)

/(pattern1)(?:.*?\1){2,}/s
Run Code Online (Sandbox Code Playgroud)

其中 s 修饰符允许点匹配换行符。