正则表达式 - 单字符子句的字符串开始和字符串锚定结束

use*_*637 5 php regex

对不起NOOB因素,但这两个regi(正则表达式复数lol)做什么不同?

http://codepad.viper-7.com/vaQTMh

    <?php

    $name = 'BartSimpson';
    $regex1 = '#^[A-Z]$#i';
    $regex2 = '#[A-Z]#i';


    if (preg_match($regex1, $name)) {
        echo "A match was found.";
    } else {
        echo "A match was not found.";
    }


    if (preg_match($regex2, $name)) {
        echo "A match was found.";
    } else {
        echo "A match was not found.";
    }

    ?>
Run Code Online (Sandbox Code Playgroud)

Mat*_*Mat 4

正如您所注意到的,第一个具有字符串锚点的开始/结束。因此,仅当您提供的字符串恰好包含范围内的一个字符时,它才会匹配[A-Z]

第二个没有锚点,匹配一个字符串,该字符串在其内容中的任何位置至少包含range 中的一个字符[A-Z]

请花一些时间阅读有关正则表达式的内容(例如此处http://www.regular-expressions.info/)。这是非常基本的。