正则表达式(Regular expresssion)

正则表达式

匹配单次
.           :匹配任意一个字符
[ ]	        :匹配[ ]里举例的任意一个字符
/d		    :匹配数字0-9
/D		    :匹配非数字 
/s			:匹配空白或tab建
/S			:匹配非空白
/w			:匹配非特殊字符,a-z, A-Z, 0-9, 汉字
/W			:匹配特殊字符

匹配不定次数
*			:匹配前一个字符出现0次到无数次
+			:匹配前一个字符出现至少一次
?			:匹配前一个字符出现1次或0次
{m}			:匹配前一个字符出现m次
```bash
[0-9]{6}匹配一串字符串的前六个数字。运用场景:假设你爬取到了手机锁屏6位密码数据库中的数据可以用它做筛选
```
{m,n}		:匹配前一个字符出现m次到n次
```bash
[0-9a-z_]{8,20}匹配长度8到20位的数字或小写字母或_,可以运用于设置密码格式
```

匹配开头或结尾
^			:匹配字符开头
$			:匹配字符结尾
[^指定字符]	:	与^[ ]完全相反,匹配不是[ ]里举例字符开头
```bash
[^a]匹配不是以字母a开头
^[a]匹配以字母a开头
```

★匹配分组相关

| :匹配左右两边任意一个正则表达式

python 复制代码
text = '123756786SSSSixstar'
text2 = 'abc'
result = re.match('^[0-9]\d*\w*|abc', text2)  # 输出:abc
result2 = re.match('^[0-9]\d*\w*|abc', text)  # 输出:123756786SSSSixstar

() :将括号作为一个分组。以下面举例解释

python 复制代码
你获取了一个有关邮箱的数据库内容,但是你不知道邮箱的格式是qq.com,163.com,139.com
data = ['123756786@qq.com', 'test@139.com', 'jdfasljsafa@163.com']
for i in range(0, len(data)):
    result = re.match('([\w]{4,20})@(qq.com|139.com|163.com)', data[i])
    print(result.group())
# 输出:123756786@qq.com
#      test@139.com
#      jdfasljsafa@163.com

一个括号是一个分组,从左到右是分组1分组2一次类推通过result.group(索引)可以返回不同的值如下

print(result.group(0))
# 输出:123756786@qq.com
#      test@139.com
#      jdfasljsafa@163.com

print(result.group(2))
#  输出:123756786
# 		test
# 		jdfasljsafa

print(result.group(2))
#  输出:qq.com
# 		139.com
# 		163.com

\num:这里的num就是分组的序号

```python
假设我要提取网页标签中源代码,例如html标签是<html></html>格式的
text = '<html>hello world</html>'
result1 = re.match('<\D*>', text)  # 输出:<html>hello world</html>
注:		\D*匹配的内容为html>hello world</html
result2 = re.match(r'<(\w*)>\w*\s\w*</\1>', text)  # 输出:<html>hello world</html>
注:		</\1>中的\1就是匹配的分组1中的\w*也就是html因为结尾也有html所以可以直接引用分组1中的内容
result3 = re.match('<(\w*)>\w*\s\w*</\\1>', text)  # 输出:<html>hello world</html>
注:		因为没有使用result2中的r模式所以要防止\1转义因此为\\1但效果一样
print(result3.group())
```

(?P<别名>):分组起别名

(?P=别名):引用别名name匹配分组字符串

```python
以之前的列子为基础进行修改取别名?P<name1>引用别名?P=name1结果如下不变
text = '<html>hello world</html>'
result1 = re.match('<(?P<name1>\w*)>\w*\s\w*</(?P=name1)>', text)  # 输出:<html>hello world</html>

```

函数

1.re.match(pattern, string)

功能:从字符串起始位置匹配正则表达式。

特点:仅检查字符串开头,若开头不匹配则返回 None。

等效于正则表达式以 ^ 开头。

```python
示例:
re.match(r'abc', 'abc123')  # 匹配成功
re.match(r'abc', '123abc')  # 匹配失败
```
  1. re.search(pattern, string)
    功能:在整个字符串中搜索第一个匹配项。
    特点:不限制匹配位置,找到第一个匹配即返回。
    即使字符串中间或结尾有匹配也会成功。
python 复制代码
示例:
re.search(r'abc', '123abc456')  # 找到 'abc'
  1. re.findall(pattern, string)
    功能:返回所有非重叠匹配项的列表。
    特点:无分组时,返回所有完整匹配的字符串列表。
    有分组时,返回分组内容的元组列表。
python 复制代码
示例:
re.findall(r'\d+', '12 apples, 34 bananas')  # ['12', '34']
re.findall(r'(\d)(\w+)', '1a 2b')  # [('1', 'a'), ('2', 'b')]
  1. re.sub(pattern, repl, string)
    功能:替换所有匹配项为指定内容。
    特点:repl 可以是字符串或函数(动态生成替换内容)。
    支持反向引用(如 \1 或 \g<1>)。
python 复制代码
示例:
re.sub(r'\d+', 'NUM', 'a1b2')  # 'aNUMbNUM'
re.sub(r'(\d{4})-(\d{2})', r'\2/\1', '2023-10')  # '10/2023'
  1. re.split(pattern, string)
    功能:按正则表达式分割字符串。
    特点:若正则含分组,分隔符会保留在结果中。
    支持复杂分隔符(如多字符或模式)。
python 复制代码
示例:
re.split(r'\d+', 'a1b22c')        # ['a', 'b', 'c']
re.split(r'(\d+)', 'a1b22c')      # ['a', '1', 'b', '22', 'c']

练习

练习题

"""
初级题目
提取所有数字
从字符串 "abc123def456ghi789" 中提取所有连续数字(结果应为 ['123', '456', '789'])。

匹配邮箱地址
从文本 "联系我:user@example.com 或 admin@test.org" 中提取所有邮箱地址(结果应为 ['user@example.com', 'admin@test.org'])。

验证日期格式
检查字符串 "2023-10-05" 是否符合 YYYY-MM-DD 格式(年范围 1900-2099,月 01-12,日 01-31)。

"""
str = "abc123def456ghi789"
result = re.findall(r'\d+', str)
print(result)
str2 = "联系我:user@example.com 或 admin@test.org"
result2 = re.findall(r'\b[\w.]+@[\w.]+\.\w+\b', str2)
print(result2)
str3 = "2023-10-30"
result3 = re.match(r'^(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$', str3)
print(result3.group())
"""
中级题目
提取带区号的电话号码
从 "电话:(021)123-4567 或 022-87654321" 中提取所有电话号码,包括括号和短横线(结果应为 ['(021)123-4567', '022-87654321'])。

匹配 HTML 标签内容
从 <div class="title">Hello World</div> 中提取标签内的内容 Hello World(不包含标签本身)。

分割混合数据
将字符串 "apple, banana; cherry|orange" 按 , ; | 或空格分割成列表(结果为 ['apple', 'banana', 'cherry', 'orange'])。
"""
str4 = "电话:(021)123-4567 或 022-87654321"
result4 = re.findall(r'\(\d{3}\)\d+-\d+|\d{3}-\d+', str4)
print(result4)
str5 = '<div class="title">Hello World</div>'
result5 = re.sub(r'<[\D]+?>', '', str5)
print(result5)
str6 = "apple, banana; cherry|orange"
result6 = re.split(r'[, ;|]+', str6)
print(result6)
"""
高级题目
排除特定模式
从文本 "error: 404, warn: 302, info: 200 OK" 中提取所有非错误状态码(即排除 error 后的数字,结果为 ['302', '200'])。

匹配嵌套 JSON 键值
从简化 JSON 片段 "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}" 中提取所有键值对(结果为 ['name', 'John', 'age', '30', 'city', 'New York'])。

复杂日期时间提取
从日志 "[2023-10-05 14:30:00] ERROR: System failure" 中提取日期和时间(结果为 ['2023-10-05', '14:30:00'])。
"""
str7 = 'error: 404, warn: 302, info: 200 OK'
result7 = re.findall(r'[0-35][0-9][0-9]', str7)
print(result7)
json_str = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}"
result = re.findall(r'"(\w+)":\s*"([^"]+)"|"(\w+)":\s*(\d+)', json_str)
print(result)
# 合并结果并过滤空值
clean_result = [tuple(filter(None, item)) for item in result]
print(clean_result)
str9 = "[2023-10-05 14:30:00] ERROR: System failure"
result9 = re.findall(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}', str9)
print(result9)
str10 = "https://example.com/search?q=python&page=2&sort=desc"
result11 = re.findall(r'[?&][\w]+=[\w]+', str10)
result12 = re.findall(r'[^?=&]+=[^&]+', str10)
result13 = re.findall(r'([^?=&]+)=([^&]+)', str10)
print(result11)
print(result12)
print(result13)
相关推荐
鸡鸭扣20 分钟前
Docker:3、在VSCode上安装并运行python程序或JavaScript程序
运维·vscode·python·docker·容器·js
paterWang1 小时前
基于 Python 和 OpenCV 的酒店客房入侵检测系统设计与实现
开发语言·python·opencv
东方佑1 小时前
使用Python和OpenCV实现图像像素压缩与解压
开发语言·python·opencv
神秘_博士2 小时前
自制AirTag,支持安卓/鸿蒙/PC/Home Assistant,无需拥有iPhone
arm开发·python·物联网·flutter·docker·gitee
Moutai码农3 小时前
机器学习-生命周期
人工智能·python·机器学习·数据挖掘
小白教程4 小时前
python学习笔记,python处理 Excel、Word、PPT 以及邮件自动化办公
python·python学习·python安装
武陵悭臾4 小时前
网络爬虫学习:借助DeepSeek完善爬虫软件,实现模拟鼠标右键点击,将链接另存为本地文件
python·selenium·网络爬虫·pyautogui·deepseek·鼠标右键模拟·保存链接为htm
代码猪猪傻瓜coding5 小时前
关于 形状信息提取的说明
人工智能·python·深度学习
码界筑梦坊6 小时前
基于Flask的第七次人口普查数据分析系统的设计与实现
后端·python·信息可视化·flask·毕业设计
微笑的Java6 小时前
Python - 爬虫利器 - BeautifulSoup4常用 API
开发语言·爬虫·python