首页 > 解决方案 > 通过忽略括号匹配模式

问题描述

我有一个字符串,我想知道模式的第一个位置。但只有在没有用括号括起来的情况下才能找到它。

示例字符串:“ This is a (first) test with the first hit

我想知道第二个first=> 32 的位置。要匹配它,(first)必须忽略它,因为它包含在括号中。

我试过这个:

preg_match(
  '/^(.*?)(first)/',
  "This is a (first) test with the first hit",
  $matches
);
$result = strlen( $matches[2] );

它工作正常,但结果是第一场比赛的位置(11)。

所以我需要改变.*?.

我试图用它替换它,.(?:\(.*?\))*?希望括号内的所有字符都将被忽略。

但这根本不匹配。

标签: phpregex

解决方案


/(?<!\()first(?!\))/

您可以使用负面展望?!运营商背后的负面看法?

preg_match(
  '/(?<!\()first(?!\))/',
  "This is a (first) test with the first hit",
  $matches
);

这仅匹配未包含在括号中的文本,或者如果不需要任何以括号开头的单词,您可以只检查单词的开头

/(?<!\()first/

推荐阅读