- 教程:www.runoob.com/regexp/rege…
- 闯关学正则表达式:codejiaonang.com/#/course/re…
- learn-regex:github.com/ziishaned/l…
元字符
| 元字符 | 描述 | |
|---|---|---|
| . | 句号匹配任意单个字符除了换行符。 例如:".ar" => The car parked in the garage. | |
| [ ] | 字符种类。匹配方括号内的任意字符。 例如:"[Tt]he" => The car parked in the garage. | |
| [^ ] | 否定的字符种类。匹配除了方括号里的任意字符 例如:"[^c]ar" => The car parked in the garage. | |
| * | 匹配>=0个重复的在*号之前的字符。 例如:“[a-z]*" => The car parked in the garage #21. | |
| + | 匹配>=1个重复的+号前的字符。 例如:"c.+t" => The fat cat sat on the mat. | |
| ? | 标记?之前的字符为可选. 例如:"[T]?he" => The car is parked in the garage. | |
| {n,m} | 匹配num个大括号之前的字符或字符集 (n <= num <= m). 例如:"[0-9]{2,3}" => The number was 9.9997 but we rounded it off to 10.0. | |
| (xyz) | 字符集,匹配与 xyz 完全相等的字符串. 匹配 pattern 并获取这一匹配。所获取的匹配可以从产生的 Matches 集合得到 可以使用分组的回溯引用,使用 \N可以引用编号为N的分组例如:"(c|g|p)ar" => The car is parked in the garage. “<p>(.*)</p>” => <p>hello</p><br> //匹配<p>hello</p>,并且提取hello "(\w)(\w)\2\1"=> allagmatic //匹配符合 ab ba 这种关系的单词 | |
| (?:pattern) | 匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹配,不进行存储供以后使用。 例如: | |
| | | 或运算符,匹配符号前或后的字符. 例如:"(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. "^(T|t)he" => The car is parked in the garage. | ||
| $ | 从末端开始匹配. 例如:"(at\.)" => The fat cat. sat. on the mat. "(at\.)$" => The fat cat. sat. on the mat. |
简写字符集
| 简写 | 描述 |
|---|---|
| . | 除换行符外的所有字符 |
| \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 行终止符 |
| \b | 匹配一个单词边界,也就是指单词和空格间的位置。 例如:“er\b” => verb never. |
| \B | 匹配非单词边界。 例如:“er\B” => verb never. |
零宽度断言(前后预查)
| 符号 | 描述 |
|---|---|
| ?= | 正先行断言-存在 在任何匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配 例如:"(T|t)he(?=\sfat)" => The fat cat sat on the mat. |
| ?! | 负先行断言-排除 在任何不匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配 例如:"(T|t)he(?!\sfat)" => The fat cat sat on the mat. |
| ?<= | 正后发断言-存在 与正向肯定预查类似,只是方向相反 例如:"(?<=(T|t)he\s)(fat|mat)" => The fat cat sat on the mat. |
| ?<! | 负后发断言-排除 与正向否定预查类似,只是方向相反 例如:"(?<!(T|t)he\s)(cat)" => The cat sat on cat. |
标志
| 标志 | 描述 |
|---|---|
| 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(.)?/gm" => The fat cat sat on the mat. |
贪婪匹配与惰性匹配
正则表达式默认采用贪婪匹配模式,在该模式下意味着会匹配尽可能长的子串。我们可以使用 ? 将贪婪匹配模式转化为惰性匹配模式。
例如:"/(.*at)/" => The fat cat sat on the mat.
"/(.*?at)/" => The fat cat sat on the mat.