Skip to main content
 首页 » 编程设计

Python 正则表达式无法按预期工作

2025年05月04日22jyk

我设计了这个正则表达式:

<entry>\\n<(\w+)>(.+?)</\w+>\\n</entry> 

解析以下RSS Feed:

<?xml version="1.0" encoding="UTF-8"?>\n<feed version="0.3" xmlns="http://purl.org/atom/ns#">\n<title>Gmail - Inbox for g.bargelli@gmail.com</title>\n<tagline>New messages in your Gmail Inbox</tagline>\n<fullcount>2</fullcount>\n<link rel="alternate" href="http://mail.google.com/mail" type="text/html" />\n<modified>2011-03-15T11:07:48Z</modified>\n<entry>\n<title>con due mail...</title>\n<summary>Gianluca Bargelli http://about.me/proudlygeek/bio</summary>\n<link rel="alternate" href="http://mail.google.com/mail?account_id=g.bargelli@gmail.com&amp;message_id=12eb9332c2c1fa27&amp;view=conv&amp;extsrc=atom" type="text/html" />\n<modified>2011-03-15T11:07:42Z</modified>\n<issued>2011-03-15T11:07:42Z</issued>\n<id>tag:gmail.google.com,2004:1363345158434847271</id>\n<author>\n<name>me</name>\n<email>g.bargelli@gmail.com</email>\n</author>\n</entry>\n<entry>\n<title>test nuova mail</title>\n<summary>Gianluca Bargelli sono tornato!?& http://about.me/proudlygeek/bio</summary>\n<link rel="alternate" href="http://mail.google.com/mail?account_id=g.bargelli@gmail.com&amp;message_id=12eb93140d9f7627&amp;view=conv&amp;extsrc=atom" type="text/html" />\n<modified>2011-03-15T11:05:36Z</modified>\n<issued>2011-03-15T11:05:36Z</issued>\n<id>tag:gmail.google.com,2004:1363345026546890279</id>\n<author>\n<name>me</name>\n<email>g.bargelli@gmail.com</email>\n</author>\n</entry>\n</feed>\n'skinner.com/products/spl]. 

问题是我没有通过使用 Python 的 re 模块 得到任何匹配:

import re 
 
regex = re.compile("""<entry>\\n<(\w+)>(.+?)</\w+>\\n</entry>""") 
regex.findall(rss_string) # Returns an empty list 

使用在线正则表达式测试器(例如 this )按预期工作,所以我认为这不是正则表达式问题。

编辑

我很清楚 using regular expressions to parse a Context-Free Grammar is BAD ,但在我的例子中,正则表达式可能仅适用于该 RSS 提要(顺便说一下,这是一个 Gmail 收件箱提要),我知道我可以使用外部库/此任务的 xml 解析器:它只是一个练习,而不是一个习惯。

问题应该是为什么下面的正则表达式在 Python 中不能按预期工作?

请您参考如下方法:

在正则表达式编译器看到一个字符串之前,Python 已经处理了斜线转义,因此你必须将它转义两次(例如 \\\\n 为 \\n )。然而,Python 对这类事情有一个方便的表示法,只需在字符串前添加一个 r:

regex = re.compile(r"""<entry>\\n<(\w+)>(.+?)</\w+>\\n</entry>""") 

顺便说一句,我同意其他人的意见,不要使用正则表达式来解析 XML。但是,希望您会发现这种字符串表示法对以后的正则表达式有所帮助。