PHP正则表达式可以随时将句子与单词匹配,只要它是';It’后面不是一个词
下面是我的一系列句子PHP正则表达式可以随时将句子与单词匹配,只要它是';It’后面不是一个词,php,regex,Php,Regex,下面是我的一系列句子 $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 Ne
$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
。不是紧挨着“A”的
如何使用regex获得预期的结果?具有负前瞻性的正则表达式应该可以做到这一点(请访问以获取工作演示): 从
PHP
实现的角度来看,您可以如下使用:
$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
具有负前瞻性的正则表达式应该可以做到这一点(请访问以获取工作演示): 从
PHP
实现的角度来看,您可以如下使用:
$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])|(a[^b])/gi
这应该可以:
/(new[^ ?york])|(a[^b])/gi
使用负前瞻使用负前瞻如果没有两边的通配符,这不是会表现得更好吗?因为您只检查文本是否存在,所以不希望匹配所有内容。vs。只是想一想,+1.你完全正确!谢谢你指出!不过,这稍微改变了比赛的处理方式。@Casimirithippolyte好吧,这就是魔法。谢谢你的反馈!!如果没有两边的通配符,这不是会表现得更好吗?因为您只检查文本是否存在,所以不希望匹配所有内容。vs。只是想一想,+1.你完全正确!谢谢你指出!不过,这稍微改变了比赛的处理方式。@Casimirithippolyte好吧,这就是魔法。谢谢你的反馈!!