【发布时间】: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应该返回什么?