Python 正则表达式不按预期工作

3 投票
4 回答
4960 浏览
提问于 2025-04-16 13:47

我写了一个正则表达式

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

用来解析以下RSS源

<?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

在网上的正则表达式测试工具(比如这个)上测试是正常的,所以我觉得这不是正则表达式的问题。

编辑

我知道用正则表达式解析上下文无关文法是个坏主意,但在我的情况下,这个正则表达式可能适用于这个RSS源(顺便说一下,这是一个Gmail收件箱的源),而且我知道我可以使用外部库/xml解析器来完成这个任务:这只是一个练习,不是一个习惯

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

4 个回答

2

不要用正则表达式来解析XML或HTML!

可以使用以下工具:

祝你好运!

补充:哦对了,这是RSS。其他人说的都对……我会在这里待一周。

4

你不应该用正则表达式来解析XML,应该使用Universal Feed Parser这个Python库。用这个库来处理XML会让你的工作简单很多,而且经过很多次的实际使用,证明它是可靠的。

我个人也用过这个库很多次,效果非常好。

6

在正则表达式编译器看到一个字符串之前,Python已经处理过反斜杠转义了,所以你需要把它转义两次(比如说,\\\\n代表\\n)。不过,Python有一个很方便的写法,专门用来处理这种情况,只需要在字符串前面加一个r

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

顺便说一下,我同意这里其他人的看法,不要用正则表达式来解析XML。不过,希望你在将来的正则表达式中能觉得这种字符串写法有用。

撰写回答