Metacharacters and escaping in regular expressions

Characters with special meanings in regular expressions are called metacharacters. Commonly used metacharacters are:

\ is generally used to escape characters
^ Asserts the starting position of the target (or the beginning of the line in multi-line mode)
$ Asserts the end position of the target (or the end of the line in multi-line mode)
. Matches any character except a newline character (Default)
[Start character class definition
] End character class definition
| Start an optional branch
(start tag of subgroup
) End tag of subgroup
? As a quantifier, indicating 0 or 1 matches. Placed after the quantifier to change the greedy nature of the quantifier. (Look up quantifiers)
*Quantifier, 0 or more matches
+ Quantifier, 1 or more matches
{custom quantifier start tag
} custom quantifier end tag

//下面的\s匹配任意的空白符,包括空格,制表符,换行符。[^\s]代表非空白符。[^\s]+表示一次或多次匹配非空白符。
$p = '/^我[^\s]+(苹果|香蕉)$/';
$str = "我喜欢吃苹果";
if (preg_match($p, $str)) {
    echo '匹配成功';
}

Metacharacters have two usage scenarios. One is that it can be used anywhere, and the other is that it can only be used within square brackets. The following are used within square brackets:

\ escape character
^ only when used as the first character (inside square brackets), indicates the character class negation
- marks the character range

Among them, ^ is outside the back brackets, indicating the starting position of the assertion target, but inside the square brackets, it represents the negation of the character class. The minus ** sign inside the square brackets can mark the character range, for example, 0-9 means between 0 and 9. of all numbers.

//下面的\w匹配字母或数字或下划线。
$p = '/[\w\.\-]+@[a-z0-9\-]+\.(com|cn)/';
$str = "我的邮箱是[email protected]";
preg_match($p, $str, $match);
echo $match[0];

Guess you like

Origin blog.csdn.net/qq_17355709/article/details/131181650