首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >xpath regex不会在lxml.etree中搜索尾部

xpath regex不会在lxml.etree中搜索尾部
EN

Stack Overflow用户
提问于 2015-06-12 04:44:28
回答 1查看 517关注 0票数 1

我正在使用lxml.etree,我正在尝试允许用户在文档中搜索文本。当用户提供搜索文本时,我使用exslt match函数在文档中查找文本。如果文本显示在element.text中,则匹配工作正常,但如果文本显示在element.tail中,则不会。

下面是一个例子:

代码语言:javascript
复制
>>> # XML as lxml.etree element
>>> root = lxml.etree.fromstring('''
...   <root>
...     <foo>Sample text
...       <bar>and more sample text</bar> and important text.
...     </foo>
...   </root>
... ''')
>>>
>>> # User provides search text    
>>> search_term = 'important'
>>>
>>> # Find nodes with matching text
>>> matches = root.xpath('//*[re:match(text(), $search, "i")]', search=search_term, namespaces={'re':'http://exslt.org/regular-expressions'})
>>> print(matches)
[]
>>>
>>> # But I know it's there...
>>> bar = root.xpath('//bar')[0]
>>> print(bar.tail)
 and important text.

我很困惑,因为text()函数本身返回所有文本--包括tail

代码语言:javascript
复制
>>> # text() results
>>> text = root.xpath('//child1/text()')
>>> print(text)
['Sample text',' and important text']

当我使用match函数时,为什么没有包含tail

EN

回答 1

Stack Overflow用户

发布于 2015-06-12 08:52:18

当我使用match函数时,为什么尾部没有包括在内?

这是因为在XPath1.0中,当给定一个节点集、match()函数(或任何其他字符串函数,如contains()starts-with()等)时。只考虑第一个节点。

您可以使用//text()并在单个文本节点上应用正则表达式匹配过滤器,然后返回文本节点的父元素,如下所示:

代码语言:javascript
复制
xpath = '//text()[re:match(., $search, "i")]/parent::*'
matches = root.xpath(xpath, search=search_term, namespaces={'re':'http://exslt.org/regular-expressions'})
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30791112

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档