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

小结

相关推荐
笨鸟先飞,勤能补拙1 天前
AI 赋能网络安全:技术全景、成熟度评估与实战案例
人工智能·python·安全·web安全·网络安全·sqlite·github
微学AI1 天前
一根针指向所有方向:挂谷猜想对 LLM Agent 技能-记忆架构的启示
开发语言·人工智能·架构·挂谷猜想
长和信泰光伏储能1 天前
京津冀光伏发电:绿色能源的未来之路
python·能源
豆瓣鸡1 天前
算法日记 - Day3
java·开发语言·算法
浦信仿真大讲堂1 天前
从重复操作到自动化闭环:如何让 CST 与 Python 真正协同起来
python·自动化·cst·仿真软件·达索软件
韭菜炒鸡肝天1 天前
VTK开发笔记(一):VTK介绍,Qt..+VSx+VTK.编译
开发语言·笔记·qt
Gu Gu Study1 天前
ScoutLoop开放域深度研究引擎(agent的初步设计想法)
人工智能·python
Aaron - Wistron1 天前
Web API C# (Furion版)带 单元测试
开发语言·后端·c#
卷无止境1 天前
写代码这件事,到底该讲究点什么?
后端·python
卷无止境1 天前
循环复杂度到底在算什么,Python 代码怎么才能写得让人一看就懂
后端·python