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

小结

相关推荐
databook10 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室10 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三12 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271115 小时前
Python之语言特点
python
刘立军15 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机19 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机20 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i21 小时前
django中的FBV 和 CBV
python·django
c8i21 小时前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python