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>
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.