python正则表达式的常见函数

import re
#正则表达式常见函数
#从源字符串的起始位置匹配一个模式,使用re.match()函数
# re.match(pattern,string,flag)#第一个参数代表正则表达式,第二个参数代表对应的源字符,第三个参数是可选参数,
#代表对应的标志位,可以放模式修正符等信息
string="apythonhellomypythonhispythonourpythonend"
pattern=".python."
result=re.match(pattern,string)
result1=re.match(pattern,string).span()#.span()设置可以过滤掉一些信息,治理下匹配成功的结果在源字符串中的位置
print(result)
print(result1)
#re.match()函数从源字符串的开头进行匹配,re.search()函数在全文中进行检索并匹配
string1="atftddpythonhellomypythonhispythonourpythonend"
pattrern1=".python."
result2=re.match(pattrern1,string1)
result3=re.search(pattrern1,string1)
print(result2)
print(result3)
#全局匹配函数
#可以发现,在以上匹配中,即使源字符串中有多个结果否和模式,也只会匹配一个结果,匹配全部内容思路如下:
#1.使用re.compile()对正则表达式进行预编译
#2.编译后,使用findall()根据正则表达式从源字符串中将匹配的结果全部找出
string2="hellomypythonhispythonourpythonend"
pattern2=re.compile(".python.")#预编译
result4=pattern2.findall(string2)#找出符合模式的所有结果
print(result4)
# 根据正则表达式来实现替换某些字符串的功能,使用re.sub()函数
# re.sub(pattern,rep,string,max)第一个参数正则表达式,第二个参数为要替换的字符串,第三个参数为源字符串
#第4个参数为最大替换次数
string3="hellomypythonhispythonourpythonend"
pattern3=".python."
resule5=re.sub(pattern3,"php",string3)#全部替换
result6=re.sub(pattern3,"php",string3,2)
print(resule5)
print(result6)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值