Python全系列 教程
3567个小节阅读:5931.1k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
代码 | 功能 |
---|---|
| | 匹配左右任意一个表达式 |
(ab) | 将括号中字符作为一个分组 |
\num | 引用分组num匹配到的字符串 |
(?P<name>) | 分组起别名 |
(?P=name) | 引用别名为name分组匹配到的字符串 |
需求:在列表中["python", "mysql", "html", "flask"],匹配python和flask
xxxxxxxxxx
import re
# 水果列表
skill_list = ["python", "mysql", "html", "flask"]
# 遍历数据
for value in skill_list:
# | 匹配左右任意一个表达式
match_obj = re.match("python|flask", value)
if match_obj:
print(f"{match_obj.group()}:需要掌握")
else:
print(f"{value}:暂时还不用掌握")
执行结果:
xxxxxxxxxx
python:需要掌握
mysql:暂时还不用掌握
html:暂时还不用掌握
flask:需要掌握
需求:匹配出163、126、qq等邮箱
xxxxxxxxxx
import re
match_obj = re.match("\w{4,20}@(163|126|qq)\.com", "hello@qq.com")
if match_obj:
print(match_obj.group())
# 获取分组数据
print(match_obj.group(1))
else:
print("匹配失败")
执行结果:
xxxxxxxxxx
hello@qq.com
需求: 匹配电话:10086
这样的数据,提取出来电话文字和电话号码
xxxxxxxxxx
import re
match_obj = re.match("(电话):([1-9]\d{4,10})", "电话:10086")
if match_obj:
print(match_obj.group())
# 分组:默认是1一个分组,多个分组从左到右依次加1
print(match_obj.group(1))
# 提取第二个分组数据
print(match_obj.group(2))
else:
print("匹配失败")
执行结果:
xxxxxxxxxx
电话
10086
需求:匹配出<html>hh</html>
xxxxxxxxxx
match_obj = re.match("<[a-zA-Z1-6]+>.*</[a-zA-Z1-6]+>", "<html>hh</div>")
if match_obj:
print(match_obj.group())
else:
print("匹配失败")
match_obj = re.match("<([a-zA-Z1-6]+)>.*</\\1>", "<html>hh</html>")
if match_obj:
print(match_obj.group())
else:
print("匹配失败")
运行结果:
xxxxxxxxxx
<html>hh</div>
<html>hh</html>
(?P<name>)
(?P=name)
需求:匹配出<html><h1>www.itbaizhan.cn</h1></html>
xxxxxxxxxx
match_obj = re.match("<(?P<name1>[a-zA-Z1-6]+)><(?P<name2>[a-zA-Z1-6]+)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itbaizhan.cn</h1></html>")
if match_obj:
print(match_obj.group())
else:
print("匹配失败")
运行结果:
xxxxxxxxxx
<html><h1>www.itbaizhan.cn</h1></html>
实时效果反馈
1: 在正则表达式(A)(B)(C)中,()代表的意思是:
A 捕获组
B 非捕获组
C 数字引用组
D 命名引用组
2: 在正则表达式(?P
A 捕获组
B 非捕获组
C 数字引用组
D 命名引用组
答案
1=>A 2=>D