【问题标题】:Regex With Negative Lookahead For Word带有负前瞻的正则表达式
【发布时间】:2020-09-09 16:09:17
【问题描述】:

使用 PCRE 风格,我试图想出一个匹配 URL 的正则表达式,只要它在 /songs/{id} 之后不包含 /foo

/songs/902   => Match
/songs/902/   => Match
/songs/902/foo   => No Match
/songs/902/foo/201/bar   => No Match
/songs/902/bar   => Match

这是我目前所拥有的^\/songs\/.+(?!\/foo).*$,但它似乎与所有给定的示例相匹配。

【问题讨论】:

  • 使用~/songs/\d+(?!.*/foo\b)~

标签: regex pcre regex-lookarounds


【解决方案1】:

您正在使用/songs/.+(?!\/foo),在贪婪的.+ 之后应用负前瞻,在/songs/ 之后,将匹配包括/foo 在内的所有内容直到结束,然后它将满足前瞻断言。您需要在匹配 /songs//songs/<digits> 之后应用前瞻断言。

您可以在 php 中使用此正则表达式,并带有负前瞻:

~/songs/\d+(?!.*/foo\b)~

RegEx Demo

正则表达式详细信息:

  • /songs/\d+:匹配 /songs/ 后跟 1+ 个数字
  • (?!.*/foo\b):如果我们在当前位置之前有/foo,则负前瞻使匹配失败。

代码:

$re = '~/songs/\d+(?!.*/foo\b)~';
preg_match_all($re, $input, $matches);

// Print the match result
var_dump($matches[0]);

【讨论】:

    【解决方案2】:

    使用

    ^\/songs\/(?!.*\/foo).+
    

    proof^\/songs\/ 在开头定位/songs/,然后(?!.*\/foo) 检查/foo 是否出现在字符串的后面,.+ 与剩下的匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2011-10-14
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多