How to use regex in XPath "contains" function

ragesh picture ragesh · Jan 28, 2014 · Viewed 139.2k times · Source

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?

Answer

Robin picture Robin · Jan 28, 2014

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')]