以下是我所拥有的一系列句子
$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'旁边。
如何使用正则表达式实现预期结果?
答案 0 :(得分:3)
具有负向前瞻的正则表达式应该可以解决问题(访问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
答案 1 :(得分:0)