【发布时间】:2017-06-23 11:06:20
【问题描述】:
我想循环查找以字符串开头并以数字结尾的元素,但我不确定如何使用 ends-with()
我这里有这段代码
*[starts-with(name(), 'cup') and ends-with(name(), '_number')]
ps:不确定应用程序使用的 xpath 版本
【问题讨论】:
我想循环查找以字符串开头并以数字结尾的元素,但我不确定如何使用 ends-with()
我这里有这段代码
*[starts-with(name(), 'cup') and ends-with(name(), '_number')]
ps:不确定应用程序使用的 xpath 版本
【问题讨论】:
这在 XPath 2.0 中是直截了当的,这里的表达式,
//*[matches(name(), '^cup.*\d$')]
将根据要求选择名称以cup 开头并以数字结尾的所有元素。
由于 XPath 1.0 缺少正则表达式 ends-with() 和测试字符串是否为数字的函数,因此使用 XPath 1.0 您的请求会变得更加复杂。这是一种可行的解决方案:
//*[starts-with(name(), 'cup')
and number(substring(name(),string-length(name())))
= number(substring(name(),string-length(name())))]
注意第二个子句是a clever way by Dimitre Novatchev to test in XPath 1.0 whether a string is a number。
这是在 XPath 1.0 中检查是否以数字结尾的更简单的方法:
//*[starts-with(name(), 'cup')
and not(translate(substring(name(),string-length(name())), '0123456789', ''))]
【讨论】:
我相信 ends-with 不在 Xpath 1.0 中,您必须使用至少 XPath 2.0 ,然后您可以使用 matches() 来匹配带有数字结尾的字符串,例如:
matches(name(), '.*\d+$')
`那么xpath将是:
*[starts-with(name(), 'cup') and matches(name(), '.*\d+$')] 或者就像@kjhughes 在他的回答中提到的那样:
*[matches(name(), '^cup.*\d+$')]
【讨论】: