正则表达式速通
正则表达式速通
Github上的正规学习地址:https://github.com/ziishaned/learn-regex
Meta Characters
| Meta character | Description | Note |
|---|---|---|
| . | Period matches any single character except a line break. | 任意字符 |
| [ ] | Character class. Matches any character contained between the square brackets. | [a-z0-9] |
| [^ ] | Negated character class. Matches any character that is not contained between the square brackets | 反 [ ] |
| * | Matches 0 or more repetitions of the preceding symbol. | [0, |
| + | Matches 1 or more repetitions of the preceding symbol. | [1, |
| ? | Makes the preceding symbol optional. | [0,1] |
| {n,m} | Braces. Matches at least “n” but not more than “m” repetitions of the preceding symbol. | (ab){3} |
| (xyz) | Character group. Matches the characters xyz in that exact order. | |
| | | Alternation. Matches either the characters before or the characters after the symbol. | |
| \ | Escapes the next character. This allows you to match reserved characters `[ ] ( ) { } . * + ? ^ $ \ | ` |
| ^ | Matches the beginning of the input. | |
| $ | Matches the end of the input. |
Shorthand Character Sets
| Shorthand | Description |
|---|---|
| . | Any character except new line |
| \w | Matches alphanumeric characters: [a-zA-Z0-9_] |
| \W | Matches non-alphanumeric characters: [^\w] |
| \d | Matches digits: [0-9] |
| \D | Matches non-digits: [^\d] |
| \s | Matches whitespace characters: [\t\n\f\r\p{Z}] (空格) |
| \S | Matches non-whitespace characters: [^\s] |
Lookarounds
| Symbol | Description | Chinese |
|---|---|---|
| ?= | Positive Lookahead | 正先行断言-存在 |
| ?! | Negative Lookahead | 负先行断言-排除 |
| ?<= | Positive Lookbehind | 正后发断言-存在 |
| ?<! | Negative Lookbehind | 负后发断言-排除 |
1 | "(T|t)he(?=\sfat)" => The fat cat sat on the mat. (The会标亮) |
Flags
用斜杠/
| Flag | Description | |
|---|---|---|
| i | Case insensitive: Match will be case-insensitive. | 忽略大小写 |
| g | Global Search: Match all instances, not just the first. | |
| m | Multiline: Anchor meta characters work on each line. | 多行修饰符(不懂) |
Greedy vs Lazy Matching
By default, a regex will perform a greedy match, which means the match will be as long as possible. We can use ? to match in a lazy way, which means the match should be as short as possible.
More
\b:单词边界
(?i):后面全部忽略大小写
学不懂,摆了
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 zhangxixi的博客!