我想使用以下正则表达式匹配以下文本 sometext12345_text
。
我在我的一项硒测试中使用它。
String expr = "//*[contains(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));
但它似乎不起作用。有人可以帮忙吗?
XPath 1.0 本身不处理正则表达式,您可以尝试类似
//*[starts-with(@id, 'sometext') and ends-with(@id, '_text')]
(正如 paul t 所指出的,如果您还需要检查中间数字,//*[boolean(number(substring-before(substring-after(@id, "sometext"), "_text")))]
可用于执行与原始正则表达式相同的检查)
在 XPath 2.0 中,尝试
//*[matches(@id, 'sometext\d+_text')]
在 Robins 的回答中,xpath 1.0 也不支持 end-with 。只支持starts-with ......所以如果你的情况不是很具体......你可以像这样使用它对我有用
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\
如果您在 Firefox 中使用 Selenium,您应该可以使用 EXSLT extensions 和 regexp:test()
这对你有用吗?
String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));
InvalidSelectorError: Unable to locate an element with the xpath expression //*[regexp:test(@id, 'sometext[0-9]+_text')] because of the following error: [Exception... "An attempt was made to create or change an object in a way which is incorrect with regard to namespaces" code: "14" nsresult: "0x8053000e (NamespaceError)" location: "<unknown>"]
感谢您的帮助。
"regexp"
前缀下注册命名空间 "http://exslt.org/regular-expressions"
的方法,它可以工作
不定期副业成功案例分享
//*[boolean(number(substring-before(substring-after(@id, "sometext"), "_text")))]
,但它高度特定于这个用例