【问题标题】:Regex returns text of every line with match, when text is inside variable当文本在变量内时,正则表达式返回每行匹配的文本
【发布时间】: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


【解决方案1】:

一个简单的衬线是:

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"]

只是事实:正则表达式太过分了但是如果你需要正则表达式:

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

【讨论】:

  • 对于正则表达式解决方案:output_lines = re.findall(r'.*Lorem.*', output) 也可以(但仍然矫枉过正)
  • @Volatility 完全一样,但是 OP 只是在使用一个例子,天知道他真正得到了什么;)
  • 不错。我的新秀开始表现出来了。尤其是因为我还没有脱离我严重过时的学校服务器的怀抱,它是 Python 的 2.4.3 版本。谢谢 K Dawg!
  • @Volatility 如果在其中找到单词 Lorem,您的正则表达式不会简单地返回整个输出吗?
  • @Seabiscuit . doesn't match newlines 除非指定了 DOTALL 标志。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 1970-01-01
  • 2021-02-14
  • 1970-01-01
  • 1970-01-01
  • 2016-04-05
相关资源
最近更新 更多