Python 当文本位于变量内部时,正则表达式返回每行匹配的文本

Python 当文本位于变量内部时,正则表达式返回每行匹配的文本,python,regex,variables,grep,Python,Regex,Variables,Grep,如何在Python中以类似于grep的方式制定正则表达式以返回找到模式的行?假设我将以下文本(通过子流程调用的shell命令的输出)分配给名为output的变量: output = "Lorem Ipsum is simply dummy text.\nLorem Ipsum has been the industry's standard\nIt has survived not only five centuries\nIt was popularised in the 1960s with

如何在Python中以类似于
grep
的方式制定正则表达式以返回找到模式的行?假设我将以下文本(通过
子流程调用的shell命令的输出)分配给名为output的变量:

output = "Lorem Ipsum is simply dummy text.\nLorem Ipsum has been the industry's standard\nIt has survived not only five centuries\nIt was popularised in the 1960s with the release of"
(很抱歉长度太长,但这更接近于一个真实的示例。因此,现在的挑战是根据
\n
拆分字符串,然后独立搜索每一行。因此,我们可以从

output_lines = re.split(r'\n', output)
然后得到一个列表,其中每个元素都是一行。我们现在有:

 >>> print output_lines
['Lorem Ipsum is simply dummy text.',
 'Lorem Ipsum has been the industry's standard',
 'It has survived not only five centuries',
 'It was popularised in the 1960s with the release of']
您建议我如何在
output\u line
中搜索包含所需图案的行,例如“Lorem”

我尝试了显而易见的方法:

for line in output_lines:
    if re.search(r"Lorem",line):
        print line

但是,有人知道一种更紧凑(可能更优雅)的方法来完成这项工作吗?

一个简单的单行程序应该是:

output_lines = [i for i in re.split(r'\n', output) if "Lorem" in i]
print output_lines
输出:

['Lorem Ipsum is simply dummy text.', "Lorem Ipsum has been the industry's standard"]
事实上:Regex太过分了,但是如果您需要Regex:


next(输出中的行对应行。如果行中有'Lorem',则拆分('\n'))
@Blender避免在评论中回答!!!!我试过了,Python抛出了一个错误。
下一个
是哪个模块的?@seabicit是它的内置模块actually@SeabiscuitK DawG在他的回答中提到了这一点——对于正则表达式解决方案,在i中使用
'Lorem'最简单:
output\u lines=re.findall(r'.*Lorem.*',output)
也会起作用(但仍然有些过分)@Volatility确切地说,OP只是使用了一个例子,天知道他真正得到了什么;)很好。我的新秀开始表现出昂首阔步的样子。不仅仅是因为我还没有脱离我严重过时的学校服务器的怀抱,它是Python的2.4.3版本。谢谢你,老兄@如果在regex中找到单词Lorem,那么它不会简单地返回整个输出吗?@seabicuite,除非指定了
DOTALL
标志。
output_lines = [i for i in re.split(r'\n', output) if re.search("Lorem",i)]