正则表达式中重复的模式 php

pattern repeated in regex php

$str='xyzab abab xhababab';

我想检查字符串是否连续3次包含ab。意思是ababab

它不起作用:

$subject = "xyzab abab xhababab";
$pattern = '/ab{3}/';
preg_match_all($pattern, $subject, $matches2,PREG_OFFSET_CAPTURE);
var_dump($matches2);

您需要将 ab 包装到一个分组结构中:

(?:ab){3}
^^^  ^

regex demo

量词应用于位于其左侧的子模式。因此,在 ab{3} 中,{3} 量化了 b 符号并且它匹配 abbb。当您对子模式序列进行分组,然后将量词设置为时,所有子模式序列都会被量化。

注意(?:...)是一个non-capturing group,只用于分组,而不是捕获(即没有为匹配的子串提供单独的内存缓冲区和这个小组)。

If you do not need the group to capture its match, you can optimize this regular expression into Set(?:Value)?. The question mark and the colon after the opening parenthesis are the syntax that creates a non-capturing group. The question mark after the opening bracket is unrelated to the question mark at the end of the regex.

IDEONE demo:

$subject = "xyzab abab xhababab";
$pattern = '/(?:ab){3}/';
preg_match_all($pattern, $subject, $matches2,PREG_OFFSET_CAPTURE);
var_dump($matches2);