如何使用re.findall(正则表达式)打印包含"开始"和"结束"字符串的文本块?



如何修改下面的脚本以包含以"word1"one_answers"word3"开头的行,因为下面的代码只打印"word2"?

期望输出:

word1
word2
word3

test.txt文件上的内容:

word0
word1
word2
word3
word4
word5

脚本:

#!/usr/bin/env python
import os, re
file = 'test.txt'
with open(file) as fp:
   for result in re.findall('word1(.*?)word3', fp.read(), re.S):
       print result

使用带有re.DOTALL标志的re.search

>>> with open('test.txt') as f:
    print re.search('word1(.*?)word3', f.read(), flags=re.DOTALL).group(0)
...     
word1
word2
word3

最新更新