dongzu3511
dongzu3511
2019-01-18 12:38

preg_match_all负向前瞻和负面后瞻

已采纳

I have this pattern which starts with (?<![\d.,]) and ends with (?![\d.,%]| %)

Why does it match 16 ?

I would expect it not to match anything in this string

$pattern = '/(?<![\d.,])-?\d{1,3}(?:(?:[. ]\d{3})*|\d*)(?:\b|[^.,%]|[,]\d{1,2})-?(?![\d.,%]| %)/';
$value = 'dag 08-16 flex pakke';

echo "pattern: $pattern
value: $value
";

preg_match_all($pattern, $value, $matches);
print_r($matches);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dsd57259 dsd57259 2年前

    Your lookarounds stand next to optional patterns, -?. Thus, whenever the lookarounds fail, backtracking occurs, and the unwelcome matches occur.

    To avoid this, account for the optional pattern inside the lookaround patterns.

    /-?(?<![\d.,]-|[\d.,])\d{1,3}(?:(?:[. ]\d{3})*|\d*)(?:\b|[^.,%]|,\d{1,2})(?!-?(?:[\d.,%]| %))-?/
       ^^^^^^^^^^^^^^^^^^^                                                   ^^^^^^^^^^^^^^^^^^^^^
    

    See the regex demo

    点赞 评论 复制链接分享

相关推荐