基本语法
.: 匹配任意单个字符(除换行符外)^: 匹配字符串的开始$: 匹配字符串的结束[]: 匹配字符集中的任何一个字符。例如,[a-z]匹配任意小写字母|: 匹配左边或右边的表达式。例如,a|b匹配'a'或'b'
量词
*: 匹配前面的字符零次或多次+: 匹配前面的字符一次或多次?: 匹配前面的字符零次或一次{n}: 匹配前面的字符恰好 n 次{n,}: 匹配前面的字符至少 n 次{n,m}: 匹配前面的字符至少 n 次,但不超过 m 次
预定义字符类
\d: 匹配任意数字,相当于[0-9]\D: 匹配任意非数字字符\w: 匹配任意字母、数字和下划线,相当于[a-zA-Z0-9_]\W: 匹配任意非字母、数字和下划线字符\s: 匹配任意空白字符(空格、制表符、换行符等)\S: 匹配任意非空白字符
分组和捕获
(): 用于分组和捕获。例如,(abc)+匹配一个或多个'abc'(?:...): 非捕获分组,用于分组但不捕获匹配的内容(?P<name>...): 捕获分组并为其指定名字。例如,(?P<year>\d{4})用于捕获年份
反向引用
\1,\2, ... : 反向引用前面捕获的组。例如,(a)\1匹配'aa'
特殊字符
\: 转义字符。例如,\.匹配点号.(?=...): 正向先行断言。例如,(?=\d)匹配紧跟在数字前的位置(?<!...): 负向先行断言。例如,(?<!\d)匹配不紧跟在数字前的位置
import re
# 查找所有数字
pattern = r'\d+'
text = 'There are 123 apples and 456 oranges.'
matches = re.findall(pattern, text)
print(matches) # 输出: ['123', '456']
# 匹配电子邮件地址
pattern = r'[\w\.-]+@[\w\.-]+'
text = 'Contact us at support@example.com or sales@example.org.'
matches = re.findall(pattern, text)
print(matches) # 输出: ['support@example.com', 'sales@example.org']
# 替换文本中的所有空白字符
pattern = r'\s+'
text = 'This is a text with extra spaces.'
replaced_text = re.sub(pattern, ' ', text)
print(replaced_text) # 输出: 'This is a text with extra spaces.'
# 匹配身份证号
pattern = r'\d{17}[\dXx]'
text = 'My ID number is 12345678901234567X.'
matches = re.findall(pattern, text)
print(matches) # 输出: ['12345678901234567X']
1. 手机号码
中国手机号码(11位数字,以1开头,第二位为3-9之间的数字)
pattern = r'^1[3-9]\d{9}$'
示例:
- 匹配:
13812345678 - 不匹配:
12345678901,1987654321
2. 身份证号码
中国身份证号(15位或18位数字,18位可包含字母X)
pattern = r'^\d{15}|\d{17}[\dXx]$'
示例:
- 匹配:
123456789012345,123456789012345678,12345678901234567X - 不匹配:
12345678901234,1234567890123456789
3. 邮箱地址
一般的邮箱地址(符合大多数邮箱格式)
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
示例:
- 匹配:
example@example.com,user.name@sub.domain.com - 不匹配:
example@com,@example.com
4. 日期(yyyy-mm-dd 格式)
日期(年-月-日,年份为四位,月份和日期为两位,支持闰年)
pattern = r'^\d{4}-\d{2}-\d{2}$'
示例:
- 匹配:
2024-08-25 - 不匹配:
2024-8-25,25-08-2024
5. 时间(hh:mm格式)
时间(24小时制,时、分、秒各为两位)
pattern = r'^\d{2}:\d{2}:\d{2}$'
示例:
- 匹配:
14:30:00 - 不匹配:
25:00:00,14:30
6. URL
一般 URL(包括 http/https,主机名,端口,路径等)
pattern = r'^(https?|ftp)://[^\s/$.?#].[^\s]*$'
示例:
- 匹配:
http://www.example.com,https://example.com/path/to/resource - 不匹配:
http://,example.com
7. IP 地址(IPv4)
IPv4 地址(四组数字,每组 0-255)
pattern = r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'
示例:
- 匹配:
192.168.1.1,255.255.255.255 - 不匹配:
256.256.256.256,192.168.1.256
8.银行卡号
银行卡号(通常为 16-19 位数字)
pattern = r'^\d{16,19}$'
示例:
- 匹配:
1234567812345678,1234567812345678901 - 不匹配:
12345678,12345678123456789012
9.车牌号码
中国车牌号码(包括字母和数字,通常为7位)
pattern = r'^[A-Z][A-Z0-9]{6}$'
示例:
- 匹配:
京A12345,粤B12345 - 不匹配:
1234A567,A1234
10.中文字符
匹配中文字符(包括汉字)
pattern = r'^[\u4e00-\u9fa5]+$'
示例:
- 匹配:
你好,测试 - 不匹配:
hello,hello 你好










