python - 如何使用正则表达式在 OPML (XML) 文件中查找带引号的属性值

标签 python xml regex opml

我正在搜索看起来像这样的 OPML 文件。我想提取大纲文本和 xmlUrl。

  <outline text="lol">
  <outline text="Discourse on the Otter" xmlUrl="http://discourseontheotter.tumblr.com/rss" htmlUrl="http://discourseontheotter.tumblr.com/"/>
  <outline text="fedoras of okc" xmlUrl="http://fedorasofokc.tumblr.com/rss" htmlUrl="http://fedorasofokc.tumblr.com/"/>
  </outline>

我的功能:

 import re
 rssName = 'outline text="(.*?)"'
 rssUrl =  'xmlUrl="(.*?)"'

 def rssSearch():
     doc = open('ttrss.txt')
     for line in doc:
        if "xmlUrl" in line:
            mName = re.search(rssName, line)
            mUrl = re.search(rssUrl, line)
            if mName is not None:
                print mName.group()
                print mUrl.group()

然而,返回值如下:

 outline text="fedoras of okc"
 xmlUrl="http://fedorasofokc.tumblr.com/rss"

rssName 和 rssUrl 的正确正则表达式是什么,以便我只返回引号之间的字符串?

最佳答案

不要使用正则表达式来解析 XML。代码很乱,容易出错的地方太多了。

例如,如果您的 OPML 提供者碰巧像这样重新格式化他们的输出会怎样:

<outline text="lol">
  <outline
      htmlUrl="http://discourseontheotter.tumblr.com/"
      xmlUrl="http://discourseontheotter.tumblr.com/rss"
      text="Discourse on the Otter"
  />
  <outline
      htmlUrl="http://fedorasofokc.tumblr.com/"
      xmlUrl="http://fedorasofokc.tumblr.com/rss"
      text="fedoras of okc"
  />
</outline>

这是完全正确的,而且意思完全一样。但是面向行的搜索和像 'outline text="(.*?)"' 这样的正则表达式会中断。

相反,请使用 XML 解析器。您的代码将更清晰、更简单、更可靠:

import xml.etree.cElementTree as ET

root = ET.parse('ttrss.txt').getroot()
for outline in root.iter('outline'):
    text = outline.get('text')
    xmlUrl = outline.get('xmlUrl')
    if text and xmlUrl:
        print text
        print xmlUrl

这会处理您的 OPML 片段和我在网上找到的类似 OPML 文件,例如 political science list .而且它非常简单,没有什么棘手的。 (我不是吹牛,这只是使用 XML 解析器而不是正则表达式所带来的好处。)

关于python - 如何使用正则表达式在 OPML (XML) 文件中查找带引号的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201513/

相关文章:

python - 如何为python for循环传递值?

python - ValueError : list. remove(x): x 不在列表中

c# - 如何从(我认为)没有标准格式的 XML 中检索值?

c# - 我的正则表达式仍在捕获未捕获的组

python - 如何返回最后一个大于 x 的元素的值

python - 附加到存储在嵌套字典中的列表

html - 在输入时自动关闭正确的 XML/HTML 标签 </

Python xml.etree 格式化美化?

javascript - 在 RegExp 构建之前清理正则表达式字符串?

自定义模板的 Javascript 字符串替换器