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

7
“我正在尝试运行一个测试,以查看具有多行的长字符串是否具有相同模式的多个出现,或者说5或10个出现。因此,像这样的字符串:”
$string = "this is a test pattern1 more of a test pattern1

and so on and so on pattern1";

所以在这种情况下,我正在尝试使用PHP:
if (preg_match('/(pattern1)\1{2,}/m',$string)) print "Found 2+ occurrences of pattern1\n";

当然这不起作用。
我不能使用 preg_match_all。
请问有人能更正我的正则表达式吗?
4个回答

3

如果我理解正确,你离好的模式不远了(这里出现了三次):

/(pattern1)(?:.*?\1){2,}/s

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


@AvinashRaj:不,我已经写了一个三次出现的例子。如果你使用懒惰量词而不是贪婪量词,你将避免许多回溯。 - Casimir et Hippolyte
@AvinashRaj:这只是一个例子,在帖子开头他写了5、10。 - Casimir et Hippolyte

1
您可以使用以下内容...
if (preg_match('/(pattern1)(?:((?!\1).)*\1){2,}/s', $string)) {

工作演示


谢谢回答。不太确定这与Casimir的回答有何不同,但我很感激您的回复。Max - Max

1
检查这个模式。
/(pattern1)/g

1
无用,请查看它是针对PHP的,使用preg_match时没有像g这样的修饰符。 - aelor

0
为什么不直接使用 preg_match_all 搜索单词/模式并计算出现次数呢?
<?php
$message="this is a test pattern1 more of a test pattern1 and one more pattern1";
echo preg_match_all('/pattern1/i', $message, $matches);

将返回3

或者在您的情况下:

<?php
$message="this is a test pattern1 more of a test pattern1 and one more pattern1";
if(preg_match_all('/pattern1/i', $message, $matches) >= 2 ) print "Found 2+ occurences of pattern1\n";

OP 表示他/她不能使用 preg_match_all - hwnd
哦,是的,但现在我在思考为什么需要 preg_match_all 却没有使用它的可能原因。 - aelor
我不能使用preg_match_all,因为我只是使用php进行测试。这是用于SpamAssassin规则的。Max - Max

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接