How to use regex in XPath "contains" function

RegexXpathSelenium WebdriverContains

Regex Problem Overview


I would like to match the following text sometext12345_text using the below regex.

I'm using this in one of my selenium tests.

String expr = "//*[contains(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));

It doesn't seem to work though. Can somebody help?

Regex Solutions


Solution 1 - Regex

XPath 1.0 doesn't handle regex natively, you could try something like

//*[starts-with(@id, 'sometext') and ends-with(@id, '_text')]

(as pointed out by paul t, //*[boolean(number(substring-before(substring-after(@id, "sometext"), "_text")))] could be used to perform the same check your original regex does, if you need to check for middle digits as well)

In XPath 2.0, try

//*[matches(@id, 'sometext\d+_text')]

Solution 2 - Regex

In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported... So if your condition is not very specific..You can Use like this which worked for me

//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\

Solution 3 - Regex

If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()

Does this work for you?

String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrageshView Question on Stackoverflow
Solution 1 - RegexRobinView Answer on Stackoverflow
Solution 2 - RegexHarish KiranView Answer on Stackoverflow
Solution 3 - Regexpaul trmbrthView Answer on Stackoverflow