正则表达式从入门到精通:实用速查手册

Raj Kumar | 2026-08-27T20:55:00 | JavaScript, Python

系统总结正则表达式常用语法,通过邮箱验证、日志解析、文本替换等 20 个实战案例强化理解。

# 正则表达式从入门到精通 ## 基础语法速查 | 语法 | 含义 | 示例 | |------|------|------| | `.` | 任意字符 | `a.c` 匹配 abc, a1c | | `*` | 0 次或多次 | `ab*c` 匹配 ac, abc, abbc | | `+` | 1 次或多次 | `ab+c` 匹配 abc, abbc | | `?` | 0 次或 1 次 | `colou?r` 匹配 color, colour | | `{n,m}` | n 到 m 次 | `a{2,4}` 匹配 aa, aaa, aaaa | | `[abc]` | 字符类 | `[aeiou]` 匹配任一元音 | | `[^abc]` | 否定字符类 | `[^0-9]` 匹配非数字 | | `\d` | 数字 | 等价于 `[0-9]` | | `\w` | 单词字符 | 等价于 `[a-zA-Z0-9_]` | | `\s` | 空白字符 | 空格、制表、换行 | | `^` | 行首 | `^Hello` | | ` 正则表达式从入门到精通:实用速查手册 | iDev Blog | 行尾 | `world 正则表达式从入门到精通:实用速查手册 | iDev Blog | ## 分组与捕获 ```python import re # 命名捕获组 pattern = r'(?P\d{4})-(?P\d{2})-(?P\d{2})' m = re.match(pattern, '2024-08-15') print(m.group('year')) # 2024 print(m.group('month')) # 08 # 非捕获组 pattern = r'(?:https?://)?(www\.example\.com)' # (?:...) 分组但不捕获 ``` ## 实战案例 ### 1. 邮箱验证 ```python email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}
#39; re.match(email_pattern, 'user@example.com') # 匹配 ``` ### 2. 手机号验证(中国大陆) ```python phone_pattern = r'^1[3-9]\d{9}
#39; re.match(phone_pattern, '13800138000') # 匹配 ``` ### 3. 提取 URL 中的域名 ```python url = 'https://www.example.com/path?query=1' domain = re.search(r'https?://([^/]+)', url).group(1) # www.example.com ``` ### 4. 日志时间提取 ```python log = '[2024-08-15 10:30:45] ERROR Connection refused' m = re.match(r'\[(.+?)\] (\w+) (.+)', log) timestamp = m.group(1) # 2024-08-15 10:30:45 level = m.group(2) # ERROR message = m.group(3) # Connection refused ``` ### 5. 密码强度校验 ```python # 至少 8 位,包含大小写字母和数字 strong_pwd = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}
#39; re.match(strong_pwd, 'Pass1234') # 匹配 ``` ### 6. 批量替换 ```python # 将驼峰命名转为下划线命名 def camel_to_snake(name): return re.sub(r'([A-Z])', r'_\1', name).lower().lstrip('_') camel_to_snake('getUserName') # get_user_name ``` ## 性能注意事项 1. 避免灾难性回溯:`(a+)+b` 在不匹配时会指数级回溯 2. 使用非贪婪匹配 `.*?` 代替贪婪 `.*` 3. 锚定开头 `^` 可以大幅提升性能 4. 预编译正则:`pattern = re.compile(r'...')` 避免重复编译 ## 在线测试工具 推荐使用 regex101.com 在线调试,支持实时匹配、解释和性能分析。

← Back to Blog