为什么 preg_match() 在部分匹配时总是验证为真? [英] Why preg_match() always validates as true when partial match?

查看:41
本文介绍了为什么 preg_match() 在部分匹配时总是验证为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近正在使用正则表达式进行实验,当我试图确认 preg_match() 函数没有返回预期结果 (false) 时.我已经意识到我的正则表达式在部分匹配和完全匹配的情况下都会评估为真.

Recently been explerimenting with regular expressions and when I've tried to confirm that the preg_match() function was not returning the expected result (false). I've realised that my regex would evaluate to true with both a partial and full match.

任何更有经验的人都可以分享一些关于为什么会这样工作的评论吗?

Can anyone more experienced share some comments on why this is working like this?

我已经使用以下代码对此进行了测试:

I've tested this using the following code:

<?php

# Storing regexp.
$pattern = "/Banana|Apples/i";

# Storing value that will be compared against regexp.
$value = "Chiiiiiiiibanana";

# Testing how preg_match is dealing with the regexp.
if (preg_match($pattern, $value, $matches)) {
    echo "It's a match!\n";

    # In case there's matches, print them.
    print_r($matches);
} else {
    echo "Sorry, not a match.";
}

?>

在这种情况下,正则表达式返回 1(真),尽管bananas"作为Chiiiiiiii"作为前缀.有什么想法吗?

In this case regex returns 1 (true) although "bananas" as "Chiiiiiiii" prefixing it. Any thoughts?

推荐答案

为了避免任何部分匹配,您必须使用锚点:

To avoid any partial matches, you must use anchors:

  • ^ - 字符串的开始
  • $ - 字符串结束.
  • ^ - start of a string
  • $ - end of string.

所以用

$pattern = "/^(?:Banana|Apples)$/i";

参见演示

由于您有一个备选列表,您需要对它们进行分组,以便锚点正确应用,而不仅仅是应用于第一个和最后一个备选方案.如果你使用"/^Banana|Apples$/i"banana会在bananasapples中匹配在 =apples 中.

Since you have an alternative list, you need to group them so that the anchors apply correctly, not just to the first and last alternatives. If you use "/^Banana|Apples$/i", banana will be matched in bananas and apples in =apples.

要仅对替代项进行分组但不存储在任何捕获组中,可以使用非捕获组 ((?:....)).此外,您不需要捕获在整个模式上设置的组,因为整个匹配文本始终存储在组 0 中.

To only group alternatives but not store in any capture groups, a non-capturing group can be used ((?:....)). Moreover, you do not need capturing groups set on the entire pattern since the whole match text is always stored inside Group 0.

这篇关于为什么 preg_match() 在部分匹配时总是验证为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆