【发布时间】:2020-02-20 07:13:50
【问题描述】:
我有一个简单的 xml:
<?xml version="1.0" encoding="utf-8" ?>
<book_list>
<book rbr="1" >
<title> Yacc </title>
<author> Filip Maric </author>
<year> 2004 </year>
<publisher> Matematicki fakultet </publisher>
<price currency="din"> 100 </price>
</book>
<book rbr="2" >
<author> Fredrik Lundh </author>
<price currency="eur"> 50 </price>
<publisher> O’Reilly & Associates </publisher>
<year> 2001 </year>
<title> Python Standard Library </title>
</book>
</book_list>
我需要用 Python 中的正则表达式匹配具有特定名称的书。我可以轻松地将任何书与:
r'<book\s*rbr="\d+"\s*>.*?</book>'
(单行模式打开),然后检查它是否正确,但是如果我想匹配特定的书 - 例如,Python标准库,直接使用正则表达式,我无法正确。如果我尝试
r'<book\s*rbr="\d+"\s*>(?P<book>.*?<title> Python Standard Library </title>.*?)</book>'
,在单行模式下,它会从头开始匹配所有内容,我明白为什么,但我找不到只匹配一个书标签的方法。我尝试了所有查找和所有不同的模式,但没有成功。
什么是正确的方法,适用于 book_list 中任意数量的书籍?
【问题讨论】:
标签: python regex pattern-matching regex-lookarounds regex-greedy