python - 使用正则表达式解析类似 xml 的文档

标签 python xml regex

我有一个包含许多类似 xml 的元素的文件,例如这个:

<document docid=1>
Preliminary Report-International Algebraic Language
Perlis, A. J. & Samelson,K.
CACM December, 1958
</document>

我需要解析 docid 和文本。什么是合适的正则表达式?

我已经试过了,但它不起作用:

collectionText = open('documents.txt').read()
docsPattern = r'<document docid=(\d+)>(.)*</document>'
docTuples = re.findall(docsPattern, collectionText)

编辑:我修改了这样的模式:

<document docid=(\d+)>(.*)</document>

不幸的是,这匹配整个文档而不是单个文档元素。

EDIT2:Ahmad 和 Acorn 的正确实现是:

collectionText = open('documents.txt').read()
docsPattern = r'<document docid=(\d+)>(.*?)</document>'
docTuples = re.findall(docsPattern, collectionText, re.DOTALL)

最佳答案

你的模式是贪心的,所以如果你有多个 <document>它最终会匹配所有元素。

您可以使用 .*? 使其成为非贪婪的,意思是“匹配零个或多个字符,尽可能少。”更新后的模式是:

<document docid=(\d+)>(.*?)</document>

关于python - 使用正则表达式解析类似 xml 的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8130828/

相关文章:

正则表达式。需要从 SVG 字符串中提取值

python - matplotlib - 如何在添加新数据时保持坐标轴不变?

python - 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) reshape 您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)

python - "scipy.sparse.issparse"是如何工作的?它总是返回 "False"

java - 当使用 java 在 xsl 样式表的帮助下替换 xml 元素时,没有被替换

c# - 查询从不返回结果 - "Enumeration yielded no results"

java - R.id 无法识别 xml id

python - 如何在没有 pymongo 命名空间的情况下导入 bson?

python - 匹配具有特定字符串的行以提取值 Python Regex

mysql - 在字符串中查找精确匹配的正则表达式可以在其他地方使用,但不能在 MySql 查询上使用