python_day19_正则表达式

正则表达式re模块

导包

python 复制代码
import re

s = "python java c c++ python2 python python3"

match 从头匹配

python 复制代码
res = re.match("python", s)
res_2 = re.match("python2", s)
print("res:", res)
print(res.span())
print(res.group())
print("res_2:", res_2)
python 复制代码
res_3 = re.search("python3", s)
print("res_3:", res_3)

findall 搜索全部匹配,返回列表

python 复制代码
res_4 = re.findall("python", s)
print("res_4:", res_4)

匹配数字,\前面加r表示转义字符无效

python 复制代码
res_5 = re.findall(r"\d", s)
print(res_5)

匹配非单词字符

python 复制代码
res_6 = re.findall(r"\W", s)
print(res_6)

匹配英文字母

python 复制代码
res_7 = re.findall(r"[a-zA-Z]", s)
print(res_7)


案例、

匹配账号,字母数字组成,长度6-10:注意{6,9}此处无空格

python 复制代码
r = r"^[a-zA-Z0-9]{6,9}$"
s = "12345Az"
print(re.findall(r, s))

匹配qq号,纯数字,首位非0,长度6-11

python 复制代码
r = r"^[1-9][0-9]{5,10}$"
r_1 = r"[1-9][0-9]{5,10}"
s = "279968894"
print(re.match(r_1, s))
print(re.findall(r, s))

匹配邮箱,qq,163,gmail

注意此处整体需加括号,否则findall返回每个分组内容

python 复制代码
# 注意此处整体需加括号,否则findall返回每个分组内容
r = r"(^[\w-]+(\.[\w-]+)*@(qq|163|gmail)(\.[\w-]+)+$)"
# s = "279968895@qq.com"
s = "a.asd.123.a_@gmail.psts.edu.cn"
print(re.findall(r, s))
print(re.match(r, s))
# 使用match取出邮箱
print(re.match(r, s).group())

小结

相关推荐
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫6 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技6 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读6 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时6 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车6 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊6 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1236 天前
2026年第38周GitHub趋势周报
python·科技·github