欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > python18 正则表达式

python18 正则表达式

2024/10/24 22:28:29 来源:https://blog.csdn.net/cjh16606260986/article/details/139856456  浏览:    关键词: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 repattern = '\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)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com