正则表达式基础速查
正则表达式(regex)是用来匹配文本的模式。每个符号称为一个记号,会改变匹配行为。下面速查列出最常用的记号,附通俗解释和可复制测试的示例。
| 记号 | 含义 | 示例 |
|---|---|---|
| . | Matches any single character except newline. | a.c matches abc, a c |
| * | Matches the preceding token zero or more times. | ab* matches a, abb |
| + | Matches the preceding token one or more times. | ab+ matches ab, abb |
| ? | Makes the preceding token optional (zero or one). | colou?r matches color, colour |
| [] | Character set: matches any one character inside. | [aeiou] matches any vowel |
| [^] | Negated set: matches any character NOT inside. | [^0-9] matches any non-digit |
| \d | Matches any digit (0-9). | \d+ matches 42, 007 |
| \w | Matches any word character (a-z, A-Z, 0-9, _). | \w+ matches hello_1 |
| \s | Matches any whitespace (space, tab, newline). | a\sb matches a b |
| ^ | Anchors the match to the start of a line/string. | ^Hello matches start of string |
| $ | Anchors the match to the end of a line/string. | world$ matches end of string |
| | | Alternation: matches the pattern on either side. | cat|dog matches cat or dog |
| () | Groups a sub-pattern (and captures it). | (ab)+ matches ab, abab |
| {n,m} | Quantifier: match the preceding token n to m times. | a{2,4} matches aa, aaaa |
| (?i) | Inline flag: makes the pattern case-insensitive. | (?i)hello matches HELLO |
说明
- 在字符集 [ ] 内,多数记号失去特殊含义。例如 [ ] 内的 . 只匹配普通的点号。
- 反斜杠(\)是转义符,可把特殊记号变为字面字符,反之亦然。
- 各引擎有差异:Python、JavaScript、PCRE、Golang 大多记号相同,但标志与环视支持不同。
常见问题
- 点号(.)匹配什么?
- 默认点号匹配除换行符外的任意单个字符。要匹配字面点号需用反斜杠转义为 \.
- * 和 + 有什么区别?
- 星号 * 匹配前面记号零次或多次,故 'ab*' 也能匹配 'a'。加号 + 至少一次,匹配 'ab' 但不匹配单独的 'a'。
- 如何匹配数字或单词字符?
- 用 \d 匹配任意数字(0-9),用 \w 匹配任意单词字符(字母、数字、下划线)。其反向为 \D 和 \W。
- ^ 和 $ 有什么用?
- ^ 把匹配锚定到字符串或行首;$ 锚定到末尾。合起来 ^pattern$ 强制整串匹配。