Python xpath正则表达式不';t在lxml.etree中搜索尾部

Python xpath正则表达式不';t在lxml.etree中搜索尾部,python,regex,xpath,lxml,Python,Regex,Xpath,Lxml,我使用的是lxml.etree,我试图允许用户在docbook中搜索文本。当用户提供搜索文本时,我使用match功能在docbook中查找文本。如果文本显示在元素.text中,则匹配工作正常,但如果文本位于元素.tail中,则匹配工作正常 下面是一个例子: >>> # XML as lxml.etree element >>> root = lxml.etree.fromstring(''' ... <root> ... <foo

我使用的是
lxml.etree
,我试图允许用户在docbook中搜索文本。当用户提供搜索文本时,我使用
match
功能在docbook中查找文本。如果文本显示在
元素.text
中,则匹配工作正常,但如果文本位于
元素.tail
中,则匹配工作正常

下面是一个例子:

>>> # 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.
当我使用
match
功能时,为什么没有包含
tail

为什么在我使用match函数时没有包含尾部

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

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

xpath = '//text()[re:match(., $search, "i")]/parent::*'
matches = root.xpath(xpath, search=search_term, namespaces={'re':'http://exslt.org/regular-expressions'})

我不能确切地告诉您要查找什么,但您可能会发现在xpath表达式中尝试字符串()而不是文本()很有用。@mehtunguh
string()
在这种情况下不起作用。虽然它确实找到了术语“important”,但它返回的
元素与匹配的文本部分相同。。。这将是一个新的问题,找出如何确定哪些文本已经匹配。。。
xpath = '//text()[re:match(., $search, "i")]/parent::*'
matches = root.xpath(xpath, search=search_term, namespaces={'re':'http://exslt.org/regular-expressions'})