Python:从文本中提取带星号的字符串

时间:2014-08-19 15:44:33

标签: python regex python-3.x

我是一个Python(和编程)菜鸟,我正在尝试使用Python 3来提取像这样的Markdown-italicised文本

*R v Stephenson*

从单独文件中的多行文本块,然后将其转储到一个集合中。我的代码如下:

import re
filename = input("Name of file: ")
readfile = open(filename, "r+").read()
cases = re.findall(r"\*.*\b\s\bv\b\s\b.*\*",readfile)
print("All cases:", cases)

它工作正常,除非在同一行中有多个斜体字块,例如:

*R v Stephenson* was a case, but so was *R v Stephens*, and the two should not be confused.

在这些情况下,它会将第一个和最后一个星号之间的整个部分添加到集合中。我如何说服Python分别处理正则表达式短语的每个实例?更重要的是,有人知道为什么会这样吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

这里的问题是,正则表达式中的*(也+?)默认情况下是贪婪的,这意味着它们会匹配尽可能多的字符。您可以使用?使正则表达式非贪婪:

cases = re.findall(r"\*.*?\b\s\bv\b\s\b.*?\*",readfile)

DEMO

Detailed Explanation