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