【问题标题】:Find string between two substrings AND between string and the end of file在两个子字符串之间以及字符串和文件末尾之间查找字符串
【发布时间】:2017-01-20 13:34:28
【问题描述】:

我有以下问题。我想从多个文本文件中获取特定的字符串,文本文件中有一定的模式。例如

example_file = "this is a test Pear this should be included1 Apple this should not be included Pear this should be included2 Apple again this should not be included Pear this should be included3"

每个文件都非常不同,但在所有文件中,我想要文本 1:在“Pear”和“Apple”这两个词之间,我已经使用以下代码解决了这个问题:

x = re.findall(r'Pear+\s(.*?)Apple', example_file ,re.DOTALL)

返回:

['this should be included1 ', 'this should be included2 ']

我无法找到的想法是我也想要最后的字符串,'this should be included3'部分。所以我想知道是否有一种方法可以用正则表达式指定类似

 x = re.findall(r'Pear+\s(.*?)Apple OR EOF', example_file ,re.DOTALL)

那么如何在单词“Pear”和 EOF(文件结尾)之间进行匹配?请注意,这些都是文本文件(所以不是一个句子)

【问题讨论】:

  • 您可能想要匹配 Pear\s+ 而不是 Pear+\s。这样你匹配 1 个或多个空白字符而不是 1 个或多个 'r' 字符 ;-)
  • 如果输入量很大,请使用r'Pear\s+([^A]*(?:A(?!pple)[^A]*)*)'
  • 当给定Pear and Pear and one Apple 应该返回什么?

标签: python regex


【解决方案1】:

选择Apple$(匹配字符串结尾的锚点):

x = re.findall(r'Pear\s+(.*?)(?:Apple|$)', example_file, re.DOTALL)

| 指定两个备选方案,(?:...) 是非捕获组,因此解析器知道选择 Apple$ 作为匹配项。

请注意,我将 Pear+\s 替换为 Pear\s+,因为我怀疑您想要匹配任意空格,而不是任意数量的 r 字符。

演示:

>>> import re
>>> example_file = "this is a test Pear this should be included1 Apple this should not be included Pear this should be included2 Apple again this should not be included Pear this should be included3"
>>> re.findall(r'Pear\s+(.*?)(?:Apple|$)', example_file, re.DOTALL)
['this should be included1 ', 'this should be included2 ', 'this should be included3']

【讨论】:

  • 我认为Pear+\s应该写成Pear\s+
  • @WiktorStribiżew:可能;它适用于演示输入,但它们可能意味着匹配一个或多个空格,而不是一个或多个 r 字符;-)
  • 您可能在非捕获组说明中的问号后面漏掉了一个冒号 (:)。
  • @Niitaku:ta,我做到了。
猜你喜欢
  • 2014-12-07
  • 2011-03-23
  • 1970-01-01
  • 2020-05-28
  • 2013-09-13
相关资源
最近更新 更多