【python】正则表达式匹配多个模式

57 篇文章 12 订阅
22 篇文章 2 订阅

利用re包的正则表达式可以便捷地得到文本中的目标

在匹配多个模式的时候,可以使用或表达式多行匹配方法来实现。

#使用或表达式来实现
#patternA|patternB,模式A 或B两种匹配
import re

text = 'This string1 is an example for match string2'
text= text.replace(' ','')   #去空格
result = re.findall(r'string1|string2',text)   #分别匹配两种模式
print(result)
#>>>['string1', 'string2']


#------------------------------------------------------------#
result2 = re.findall(r'This(.*?)isanexampleformatch(.*$)',text)
print(result2)
#可同时输出两个或多个匹配的结果
#>>>[('string1', 'string2')]


#------------------------------------------------------------#
#当带匹配文档包含多行时,需要使用re.S来开启多行模式
text_multi = 'This string1 is \n an example \n for match string2'
text_multi = text_multi .replace(' ','')   #去空格
result3 = re.findall(r'string(.*?)',text_multi,re.S)   #利用re.S开启多行模式来忽略\n换行
print(result3)
#输出
#>>>['string1', 'string2']

在这里插入图片描述
pic form pexels


ref:
https://blog.csdn.net/u010042787/article/details/78488308
bs:
https://blog.csdn.net/abclixu123/article/details/38502993
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id17
http://www.cnblogs.com/csj007523/p/7641749.html
re.S:http://www.cnblogs.com/xieqiankun/p/re-sinpython.html

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值