【问题标题】:PHP Regex match sentence with word anytime when it's not a followed by another wordPHP Regex 将句子与单词匹配,当它不是后面跟着另一个单词时
【发布时间】:2018-03-11 12:46:52
【问题描述】:

下面是我的句子数组

$strings = [ 
  "I want to match docs with a word New", 
  "But I don't want to match docs with a phrase New York", 
  "However I still want to match docs with a word New which has a phrase New York", 
  "For example let's say there's a New restaraunt in New York and I want this doc to be matched."
] 

我想将上面的句子与单词 new 字符串匹配。但我不想匹配 new 后跟 york 的句子。我希望能够匹配任何单词A 前面/后面没有单词B 在一些小的单词距离N 内。不在“A”旁边。

如何使用正则表达式达到预期效果?

【问题讨论】:

  • 使用负前瞻(?!)

标签: php regex


【解决方案1】:

带有负前瞻的正则表达式应该可以解决问题(访问 this link 以获得有效的演示):

.*[Nn]ew(?! [Yy]ork).*

PHP实现的角度来看,您可以使用preg_match function如下:

$strings = [ 
    "I want to match docs with a word New", 
    "But I don't want to match docs with a phrase New York", 
    "However I still want to match docs with a word New which has a phrase New York", 
    "For example let's say there's a New restaraunt in New York and I want this doc to be matched."
];

foreach ($strings as $string) {
    echo preg_match('/.*new(?! york).*/i', $string)."\n";
}

输出是:

1 -> Match
0 -> Discarded
1 -> Match
1 -> Match

【讨论】:

  • 如果没有通配符,这会不会表现得更好?由于您只检查文本是否存在,因此您不想匹配所有内容。 .*new(?! york).*, 212 stepsnew(?! york) 64 steps。只是一个想法,+1。
  • 你完全正确!感谢您指出!不过,这会稍微改变必须处理匹配的方式。
  • @CasimiretHippolyte 好吧,这就是魔法。感谢您的反馈!
【解决方案2】:

这应该可行:

/(new[^ ?york])|(a[^b])/gi

DEMO

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 2014-04-20
    相关资源
    最近更新 更多