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

利用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 
 an example 
 for match string2'
text_multi = text_multi .replace(' ','')   #去空格
result3 = re.findall(r'string(.*?)',text_multi,re.S)   #利用re.S开启多行模式来忽略
换行
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

原文地址:https://www.cnblogs.com/Tom-Ren/p/10024293.html