我有这篇文章,我想搜索“工作”这个词,除了“在工作培训上”或一个短语列表。如果我使用这个preg_match http://regexr.com/3dlo7
我得到三个结果..。但我只想要第一次和第三次
这是一份好工作,这是在职培训。干得好
对preg_match有什么想法吗?
发布于 2016-06-21 11:52:49
首先,当您想要测试用于PHP的正则表达式时,不要使用为Javascript设计的RegExr,您可以使用regex101.com或regex.larsolavtorvik.com
您可以这样设计您的模式:
\bjob\b(?!(?<=\bon the job) training\b)如果你想排除其他情况:
\bjob\b(?!(?<=\bon the job) training\b|(?<=\bthe job) I hate\b)您还可以使用(*SKIP)(*F)模式(这会使子模式失败,并强制已经匹配的字符被跳过),它可以更容易编写,但效率较低(因为模式在一开始就有变化)
\b(?:on the job training\b(*SKIP)(*F)|the job I hate\b(*SKIP)(*F)|job\b)您可以使用第一个字符识别技巧对其进行一些改进,从而在不感兴趣的位置上迅速失败:
\b(?=[otj])(?:on the job training\b(*SKIP)(*F)|the job I hate\b(*SKIP)(*F)|job\b)发布于 2016-06-21 11:27:13
使用环顾四周怎么样?
$str = 'This is a good job and this is on the job training. Nice job';
preg_match_all('/(?<!on the )\bjob\b(?! training)/', $str, $m);
print_r($m);输出:
Array
(
[0] => Array
(
[0] => job
[1] => job
)
)发布于 2016-06-21 11:32:28
使用这个正则表达式:-
\bjob(?!\straining)\bhttp://regexr.com/3dloj
在您的评论之后,您还希望在单词之前排除单词,然后使用下面的regex:-
\b(?<!Nice\s)job(?!\straining)\b // exclude Nice wordhttp://www.phpliveregex.com/p/g8h
(?<!Nice\s)job与没有在"Nice "前面的Nice "job"匹配,使用的是负查找。
https://stackoverflow.com/questions/37942865
复制相似问题