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())

小结

相关推荐
吃我一窝jio34 分钟前
Python与Go线程模型深度对比
java·开发语言·python
eggwyw1 小时前
C++ union 的一种妙用法
开发语言·c++
zwd20051 小时前
Manim 怎么放大画面的某一部分?
python·动画·可视化·manim·数学动画
屿华AI2 小时前
AUTOSAR 实战-诊断工具 | UDS 0x27 安全访问的配置化实现:种子密钥算法插件化设计
python·测试工具·汽车
RobinDevNotes2 小时前
Claude Code 剪视频,不上传、不要 API Key
人工智能·python·音视频·开发工具·ipython
starzy19903 小时前
深入理解Scala隐式函数:自动类型转换
开发语言·后端·scala
如夏倾城4 小时前
VRRP(虚拟路由器冗余协议Virtual Router Redundancy Protocol)
网络·python·网络协议·安全·智能路由器·负载均衡·信息与通信
IvanCodes4 小时前
LangChain(04):Runnable 与 LCEL 的执行与组合机制
python·langchain·agent
特创数字科技4 小时前
纯本地离线运行的文档脱敏工具(技术分享)
前端·驱动开发·python
布莱克6055 小时前
Swift 循环与控制转移详解:从 for-in 到标签跳转
开发语言·ssh·swift·循环