【发布时间】:2013-12-23 05:53:22
【问题描述】:
如何在 Python 中制定一个正则表达式,以类似grep 的方式返回找到该模式的行?假设我有以下文本(使用 subprocess 调用的 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_lines 中搜索包含我请求的模式的行,比如“Lorem”?
我尝试了显而易见的:
for line in output_lines:
if re.search(r"Lorem",line):
print line
而且它有效。但是,有没有人知道更紧凑(可能更优雅)的方式来完成这项工作?
【问题讨论】:
-
next(line for line in output.split('\n') if 'Lorem' in line) -
@Blender 避免在 cmets 中回答!!!
-
我试过了,Python 抛出了一个错误。
next来自哪个模块? -
@Seabiscuit 其实是内置的
-
@Seabiscuit K DawG 已经在他的回答中提到了 - 最简单的方法是使用
'Lorem' in i
标签: python regex variables grep