正则表达式完全指南:30分钟从小白到上手

正则表达式(Regex)是每个程序员都该会的文本处理利器。不管是日志分析、表单验证、还是代码搜索,正则都能让你事半功倍。

一、基础语法

.     匹配任意单个字符(除换行)
\d    匹配数字 [0-9]
\w    匹配字母数字下划线 [a-zA-Z0-9_]
\s    匹配空白字符(空格、Tab、换行)
^     匹配开头
$     匹配结尾
*     0次或多次
+     1次或多次
?     0次或1次
{n}   恰好n次
{n,}  至少n次
{n,m} n到m次

二、常用模式

# 手机号
^1[3-9]\d{9}$

# 邮箱
^[\w\.-]+@[\w\.-]+\.\w{2,}$

# URL
^https?://[\w\.-]+\.\w{2,}(/[\w\.-]*)*/?$

# IP地址
^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$

# 中文
[一-龥]

三、Python 实战示例

import re

text = "联系我们:邮箱 support@example.com,电话 13800138000"

# 提取邮箱
emails = re.findall(r'[\w\.-]+@[\w\.-]+\.\w{2,}', text)
print(emails)  # ['support@example.com']

# 提取手机号
phones = re.findall(r'1[3-9]\d{9}', text)
print(phones)  # ['13800138000']

# 替换敏感信息
masked = re.sub(r'1[3-9]\d{9}', '****', text)
print(masked)  # 联系我们:邮箱 support@example.com,电话 ****

四、分组与捕获

# 分组用 ()
pattern = r'(\d{4})-(\d{2})-(\d{2})'
text = "日期: 2024-03-15"

match = re.search(pattern, text)
print(match.group(1))  # 2024
print(match.group(2))  # 03
print(match.group(3))  # 15

# 命名分组 (?P...)
pattern = r'(?P\d{4})-(?P\d{2})-(?P\d{2})'
match = re.search(pattern, text)
print(match.group('year'))  # 2024

五、在线工具推荐

  • regex101.com — 最强大的正则测试和调试工具
  • regexr.com — 交互式学习平台
  • regulex.com — 正则可视化

正则不用死记,收藏这张速查表,需要的时候翻出来用就行。写多了自然就熟了。