猿问

负后视正则表达式在 PHP 中不起作用

我用 PHP 编写了一段代码,旨在匹配一个副词(以“ly”结尾的单词),该副词不应匹配任何单词 daily、weekly、monthly、bi-daily、bi-weekly 等。


例如,给定句子Locally meet daily for 3 days, only Locallyshould match。


我使用负向后看确定了 Regex 语法,但 PHP 向我抛出一个错误:


编译失败:lookbehind 断言在偏移处不是固定长度..


这是我在 PHP 中的完整代码:


<?php

$sentence = "Locally meet daily for next 3 days";


// Use preg_match() function to check match 

preg_match('/(\w+ly)(?<!(daily|weekly|monthly))/', $sentence, $matches, PREG_OFFSET_CAPTURE); 


// Display matches result 

print_r($matches); 

我试过负面前瞻,但它并没有给我带来可喜的结果。有人会建议可以做什么吗?谢谢


哆啦的时光机
浏览 131回答 1
1回答

慕哥6287543

您可以使用否定前瞻,但它需要在您的匹配组之前。您还需要在正则表达式的开头添加一个断字 ( \b) 断言,以便(例如)正则表达式不匹配ailyin daily,另一个在末尾,这样您就不会ly在中间匹配单词 with 例如newlywed:$sentence = "Locally meet daily newlywed for next 3 days";preg_match_all('/\b(?!(?:daily|weekly|monthly))(\w+ly)\b/', $sentence, $matches, PREG_OFFSET_CAPTURE);&nbsp;print_r($matches);&nbsp;输出:Array(&nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => Locally&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [1] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => Array&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => Locally&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; ))3v4l.org 上的演示
随时随地看视频慕课网APP
我要回答