使用正则表达式跳过所有字符,直到找到使用负向前瞻的特定字母序列

pha*_*zei 6 php regex negative-lookahead

我对基本的正则表达式很好,但是我在pos/neg的前方/后方有点迷失.

我正试图从中提取id#:

[keyword stuff=otherstuff id=123 morestuff=stuff]

之前或之后可能会有无限量的"东西".我一直在使用The Regex Coach来帮助调试我尝试过的东西,但我不再向前推进......

到目前为止我有这个:

\[keyword (?:id=([0-9]+))?[^\]]*\]
Run Code Online (Sandbox Code Playgroud)

这会在id之后处理任何额外的属性,但我无法弄清楚如何忽略关键字和id之间的所有内容.我知道我不能去,[^id]* 我相信我需要使用像这样的负面预测,(?!id)*但我想因为它是零宽度,它不会从那里向前移动.这也不起作用:

\[keyword[A-z0-9 =]*(?!id)(?:id=([0-9]+))?[^\]]*\]
Run Code Online (Sandbox Code Playgroud)

我一直在寻找各种例子,但没有找到任何例子.或者也许我有,但他们走到了我的脑海,我甚至没有意识到他们是什么.

救命!谢谢.

编辑:它必须匹配[keyword stuff = otherstuff],其中id =根本不存在,所以我必须在id#group上有1或0.还有其他[otherkeywords id = 32]我不想匹配.该文档需要使用preg_match_all在整个文档中匹配多个[keyword id = 3].

Wri*_*ken 2

无需前瞻/后瞻:

/\[keyword(?:[^\]]*?\bid=([0-9]+))?[^\]]*?\]/
Run Code Online (Sandbox Code Playgroud)

添加结尾“[^]]*]”来检查真正的标签结尾,可能是不必要的。

编辑:将 \b 添加到 id,否则它可以匹配[keyword you-dont-want-this-guid=123123-132123-123 id=123]

$ php -r 'preg_match_all("/\[keyword(?:[^\]]*?\bid=([0-9]+))?[^\]]*?\]/","[keyword stuff=otherstuff morestuff=stuff]",$matches);var_dump($matches);'
array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(42) "[keyword stuff=otherstuff morestuff=stuff]"
  }
  [1]=>
  array(1) {
    [0]=>
    string(0) ""
  }
}
$ php -r 'var_dump(preg_match_all("/\[keyword(?:[^\]]*?\bid=([0-9]+))?[^\]]*?\]/","[keyword stuff=otherstuff id=123 morestuff=stuff]",$matches),$matches);'
int(1)
array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(49) "[keyword stuff=otherstuff id=123 morestuff=stuff]"
  }
  [1]=>
  array(1) {
    [0]=>
    string(3) "123"
  }
}
Run Code Online (Sandbox Code Playgroud)