python正則表示式筆記——匹配多行多段
阿新 • • 發佈:2021-02-19
技術標籤:python自動化運維工具正則表示式python運維linux
場景分析
使用python正則表示式提取某段中多行內容,例如:
‘’’
aaaa bbbb cccc
xx abcdefg
abcdefg
abc yy
abc abde adf
dadfeljgslka lkdsjgls
xx adgei ,
fdasd yy
adg asfgk ksdg
adsa xx
dga dgl yy
alkdg
‘’’
提取被xx
和yy
包圍的欄位
不使用compile
with open('./filename.txt', 'r') as f:
content = f.read( )
import re
re_str = r'xx.+yy' # the resp will not include 'xx' and 'yy' if you use the 'xx(.+)yy'
resp = re.findall(re_str, content, re.S)
print resp
使用compile
with open('./filename.txt', 'r') as f:
content = f.read()
import re
re_str = r'xx.+yy' # the resp will not include 'xx' and 'yy' if you use the 'xx(.+)yy'
comp = re.compile(re_str, re.S)
resp = comp.findall(content)
print resp