我已经制作了这个正则表达式:
<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 [email protected]</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/[email protected]&message_id=12eb9332c2c1fa27&view=conv&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.barg[email protected]</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/[email protected]&message_id=12eb93140d9f7627&view=conv&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>[email protected]</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)按预期工作,所以我认为不是正则表达式问题。
Edit
我很清楚使用正则表达式来解析上下文无关语法是不好的,但就我而言,正则表达式可能有效only对于 RSS feed(顺便说一句,它是 Gmail 收件箱 feed),我知道我可以使用外部库/xml 解析器来完成此任务:它只是一个exercise,不是一个habit.
问题应该是为什么下面的正则表达式在 Python 中不能按预期工作?
在正则表达式编译器看到字符串之前,Python 已经处理了斜杠转义符,因此您必须将其转义两次(例如\\\\n
for \\n
)。然而,Python 对于这类事情有一个方便的表示法,只需粘贴一个r
字符串之前:
regex = re.compile(r"""<entry>\\n<(\w+)>(.+?)</\w+>\\n</entry>""")
顺便说一下,我同意其他人的观点,不要使用正则表达式来解析 XML。但是,希望您会发现此字符串表示法对将来的正则表达式很有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)