正则表达式深入浅出
2024-07-04 14:46:58 0 举报
AI智能生成
正则表达式深入浅出
作者其他创作
大纲/内容
1.基本匹配
⼀些字⺟和数字组合
"the" => The fat cat sat on <b>the</b> mat.
2.元字符
点运算符 .
匹配任意单个字符,但不匹配换⾏符
".ar" => The <b>car</b> <b>par</b>ked in the <b>gar</b>age.
字符集 []
⽅括号中指定字符集的范围
"[Tt]he" => <b>The</b> car parked in <b>the</b> garage.
⽅括号的句号就表示句号
"ar[.]" => A garage is a good place to park a c<b>ar.</b>
否定字符集 ^
匹配除了⽅括号⾥的任意字符
"[^c]ar" => The car <b>par</b>ked in the <b>gar</b>age.
重复次数
* >=0 次
"\s*cat\s*" => The fat<b> cat </b>sat on the con<b>cat</b>enation.
+ >=1 次
"c.+t" => The fat <b>cat sat on the mat</b>.
? 0或1 次
"[T]?he" => <b>The</b> car is parked in t<b>he</b> garage.
{} 范围次
"[0-9]{2,3}" => The number was 9.<b>999</b>7 but we rounded it off to <b>10</b>.0.
() 特征标群
括号中包含的内容将会被看成⼀个整体
"(c|g|p)ar" => The <b>car</b> is <b>par</b>ked in the <b>gar</b>age.
| 或运算符
"(T|t)he|car" => <b>The car</b> is parked in <b>the</b> garage.
\ 转码特殊字符
{ } [ ] / \ + * . $ ^ | ?
"(f|c|m)at\.?" => The <b>fat cat</b> sat on the <b>mat.</b>
锚点
^匹配字符串的开头
"^(T|t)he" => <b>The</b> car is parked in the garage.
$匹配字符是否是最后
"(at\.)$" => The fat cat. sat. on the m<b>at.</b>
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)" => <b>The</b> fat cat sat on the mat.
xxx(?!...) 负先⾏断⾔
"(T|t)he(?!\sfat)" => The fat cat sat on <b>the</b> mat.
(?<=...)xxx 正后发断⾔
"(?<=(T|t)he\s)(fat|mat)" => The <b>fat</b> cat sat on the <b>mat</b>.
(?<!...)xxx 负后发断⾔
"(?<!(T|t)he\s)(cat)" => The cat sat on <b>cat</b>.
5.标志
i 忽略⼤⼩写
"The" => <b>The</b> fat cat sat on the mat.
"/The/gi" => <b>The</b> fat cat sat on <b>the</b> mat.
g 全局搜索
"/.(at)/" => The <b>fat</b> cat sat on the mat.
"/.(at)/g" => The <b>fat cat sat</b> on the <b>mat</b>.
m 多⾏修饰符
"/.at(.)?$/" => The fat\n cat sat\n on the <b>mat.</b>
"/.at(.)?$/gm" => The <b>fat</b>\n cat <b>sat</b>\n on the <b>mat.</b>
6.贪婪匹配与惰性匹配
贪婪匹配(默认)
"/(.*at)/" => <b>The fat cat sat on the mat</b>.
惰性匹配(?转换)
"/(.*?at)/" => <b>The fat</b> cat sat on the mat.
0 条评论
下一页