python18 正则表达式

python18 正则表达式

复制代码
正则表达式 re.match(),re.search(),re.findall(),re.sub(),re.split()
元字符 具有特殊意义的专用字符
导入模块
improt re

代码

复制代码
'''
正则表达式 re.match(),re.search(),re.findall(),re.sub(),re.split()
元字符 具有特殊意义的专用字符
导入模块
improt re
'''
import re

pattern = '\d\.\d+' # +限定符, \d 0-9 数字出现1次或多次
s = 'I study Python 3.11 every day'
# 从字符串的开始位置进行匹配,如果起始位置匹配成功,成功为match对象,否则为None
# re.match(匹配规则,等匹配字符串,re.I 忽略大小写)
match = re.match(pattern,s,re.I)
print(match) #None
s2 = '3.11Python I study every day'
match2 = re.match(pattern,s2,re.I)
print(match2)  #<re.Match object; span=(0, 4), match='3.11'> 找到结果了
# 获取数据
print('匹配值的起始位置:',match2.start())
print('匹配值的结束位置:',match2.end())
print('匹配区间的位置元素:',match2.span())
print('待匹配的字符串:',match2.string)
print('匹配的数据:',match2.group())

# re.search() 用于在整个字符串中搜索第一个匹配的值,如果匹配成功,结果为match对象,否则为None
s3 = 'I study Python3.11 every day Python2.7 I love you'
match3 = re.search(pattern,s3)
print(f'search()=>{match3}')

s4 = '4.10 I study Python3.11 every day Python2.7 I love you'
match4 = re.search(pattern,s4)
print(f'search()=>{match4}')

s5 = 'I study Python every day Python I love you'
match5 = re.search(pattern,s5)
print(f'search()=>{match5}')

# re.findall() 用于在整个字符串搜索所有符合正则表达式的值,结果为一个列表类型
s6 = 'I study Python3.11 every day Python2.7 I love you'
match6 = re.findall(pattern,s6)
print(f'findall()=>{match6}')

# re.sub() 用于实现对字符串中指定子串的替换
pattern = '黑客|破解|反爬'
s7 = '我想学习Python,想破解一些VIP视频,Python可以实现无底线反爬吗?'
newS7 = re.sub(pattern,'xxx',s7)
print(f'sub()替换后:{newS7}')

# re.split() 与字符串的split方法功能相同,都是分隔字符串
pattern2 = '[?l&]'
s8 = 'https://www.baidu.com/s?wd=ysj&rsv_spt=1'
lst = re.split(pattern2,s8)
print(lst)
相关推荐
西岸行者4 天前
学习笔记:SKILLS 能帮助更好的vibe coding
笔记·学习
starlaky4 天前
Django入门笔记
笔记·django
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》1-Introduction_介绍
笔记·langchain·吴恩达
悠哉悠哉愿意4 天前
【单片机学习笔记】串口、超声波、NE555的同时使用
笔记·单片机·学习
勇气要爆发4 天前
吴恩达《LangChain LLM 应用开发精读笔记》2-Models, Prompts and Parsers 模型、提示和解析器
android·笔记·langchain
qianshanxue114 天前
计算机操作的一些笔记标题
笔记
土拨鼠烧电路4 天前
笔记11:数据中台:不是数据仓库,是业务能力复用的引擎
数据仓库·笔记
土拨鼠烧电路4 天前
笔记14:集成与架构:连接孤岛,构建敏捷响应能力
笔记·架构
烟花落o4 天前
栈和队列的知识点及代码
开发语言·数据结构·笔记·栈和队列·编程学习