Python入门篇【正则表达式】

Python【正则表达式】


文章目录


提示:以下是本篇文章正文内容,下面案例可供参考

一、基础匹配

正则表达式,又称规则表达式(Regular Expression),是使用单个字符串来描述、匹配某个句法规则的字符串,常被用来检索、替换那些符合某个模式(规则)的文本。->用正则表达式来判断字符串是否符合匹配规则。

  • match():从头开始匹配,匹配成功返回匹配对象,不成功返回None【左开右闭】
  • search():搜索整个字符串,从前向后搜索,找到就停止,不会再向后搜索
  • findall():全局搜索,以列表形式返回
  • span():字符串位置
  • group():把匹配到的【完整字符串】提取出来
python 复制代码
import re

s = 'python demo341@python2342`%(*&$(ima!!dsaf45612344'  # 定义字符串

r1 = re.match('python', s)  # 从头检索,不匹配返回None
r2 = re.search('python', s)  # 进行搜索,识别到第一个,不在进行后续识别
r3 = re.findall('python', s)  # 列表形式返回指定字符串
print(r1)
print(r1.span())  # 展示字符串所在位置[m,n-1][左闭右开]
print(r1.group())  # 把匹配到的【完整字符串】提取出来
print(r2)
print(r3)

二、元字符匹配

2.1 元字符匹配

python 复制代码
import re

s = 'python demo341@python2342`%(*&$(ima!!dsaACf45612344'  # 定义字符串
r4 = re.findall(r'\d', s)  # 找出字符串中全部的数字,r表示避免被识别为转义字符!!!
r5 = re.findall(r'\W', s)  # 找出特殊字符
r6 = re.findall(r'[a-zA-Z0-9]', s)  # 找出全部的英文字母和数字,可以设置范围,例如只想找5-9的数字,则设置为[5-9]
print(r4)
print(r5)
print(r6)

python 复制代码
import re

# 这就是我们一起打磨的终极正则!
email_pattern = r'^[a-zA-Z0-9]+([_\-\.][a-zA-Z0-9]+)*@(qq|163|gmail)\.(com|cn)'

# 测试函数
def check_email(email):
    if re.fullmatch(email_pattern, email):
        return f"✅ {email} ------ 合法邮箱"
    else:
        return f"❌ {email} ------ 非法邮箱"

# 开始测试
print(check_email("zhang.san@qq.com"))       # 合法
print(check_email("li_si123@163.cn"))       # 合法
print(check_email("wang-wu@gmail.com"))     # 合法
print(check_email("zhao.liu@sina.com"))     # 非法(服务商不对)
print(check_email("-zhang@qq.com"))          # 非法(符号开头)
print(check_email("zhang..san@qq.com"))      # 非法(连续符号)
print(check_email("zhang@qq.com123"))       # 非法(后缀不对)

相关推荐
花酒锄作田17 小时前
Pydantic校验配置文件
python
hboot17 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi1 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi1 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽1 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187911 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L2 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅2 天前
海天线算法的前世今生
python·计算机视觉
韩师傅2 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L2 天前
LangGraph的MessageState and HumanMessage
python