正则表达式深入浅出
2024-07-04 14:46:58 0 举报
AI智能生成
正则表达式深入浅出
作者其他创作
大纲/内容
1.基本匹配
⼀些字⺟和数字组合
"the" => The fat cat sat on the mat.
2.元字符
点运算符 .
匹配任意单个字符,但不匹配换⾏符
".ar" => The car parked in the garage.
字符集 []
⽅括号中指定字符集的范围
"[Tt]he" => The car parked in the garage.
⽅括号的句号就表示句号
"ar[.]" => A garage is a good place to park a car.
否定字符集 ^
匹配除了⽅括号⾥的任意字符
"[^c]ar" => The car parked in the garage.
重复次数
* >=0 次
"\s*cat\s*" => The fat cat sat on the concatenation.
+ >=1 次
"c.+t" => The fat cat sat on the mat.
? 0或1 次
"[T]?he" => The car is parked in the garage.
{} 范围次
"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0.
() 特征标群
括号中包含的内容将会被看成⼀个整体
"(c|g|p)ar" => The car is parked in the garage.
| 或运算符
"(T|t)he|car" => The car is parked in the garage.
\ 转码特殊字符
{ } [ ] / \ + * . $ ^ | ?
"(f|c|m)at\.?" => The fat cat sat on the mat.
锚点
^匹配字符串的开头
"^(T|t)he" => The car is parked in the garage.
$匹配字符是否是最后
"(at\.)$" => The fat cat. sat. on the mat.
3.简写字符集
任意
.
除换⾏符外的所有字符
字⺟
\w
匹配所有字⺟数字,等同于 [a-zA-Z0-9_]
\W
匹配所有⾮字⺟数字,即符号,等同于: [^\w]
数字
\d
匹配数字: [0-9]
\D
匹配⾮数字: [^\d]
空格
\s
匹配所有空格字符,等同于: [\t\n\f\r\p{Z}]
\S
匹配所有⾮空格字符: [^\s]
特殊
\f
匹配⼀个换⻚符
\n
匹配⼀个换⾏符
\r
匹配⼀个回⻋符
\t
匹配⼀个制表符
\v
匹配⼀个垂直制表符
\p
匹配 CR/LF(等同于 \r\n ),⽤来匹配 DOS ⾏终⽌符
4.零宽度断⾔(前后预查)
xxx(?=...) 正先⾏断⾔
"(T|t)he(?=\sfat)" => The fat cat sat on the mat.
xxx(?!...) 负先⾏断⾔
"(T|t)he(?!\sfat)" => The fat cat sat on the mat.
(?<=...)xxx 正后发断⾔
"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat.
(?<!...)xxx 负后发断⾔
"(?<!(T|t)he\s)(cat)" => The cat sat on cat.
5.标志
i 忽略⼤⼩写
"The" => The fat cat sat on the mat.
"/The/gi" => The fat cat sat on the mat.
g 全局搜索
"/.(at)/" => The fat cat sat on the mat.
"/.(at)/g" => The fat cat sat on the mat.
m 多⾏修饰符
"/.at(.)?$/" => The fat\n cat sat\n on the mat.
"/.at(.)?$/gm" => The fat\n cat sat\n on the mat.
6.贪婪匹配与惰性匹配
贪婪匹配(默认)
"/(.*at)/" => The fat cat sat on the mat.
惰性匹配(?转换)
"/(.*?at)/" => The fat cat sat on the mat.
0 条评论
下一页