Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use regex in XPath "contains" function

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?

like image 455
ragesh Avatar asked Jan 28 '14 12:01

ragesh


People also ask

Can we use contains in XPath?

contains() in Selenium is a function within Xpath expression which is used to search for the web elements that contain a particular text. We can extract all the elements that match the given text value using the XPath contains() function throughout the webpage.

How do you write contain in XPath?

The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]

What is XPath and regex?

XPath regex is help us using locate the part of an attribute that stays consistent for identifying the element of the web in a web page. Sometimes value from the attribute of html code is changed, the attribute of the instance is changing every time and the web page which we are working on is refreshed every time.

How do I use regular expressions in Selenium locators?

We can use regex in locators in Selenium webdriver. This can be achieved while we identify elements with the help of xpath or css locator. Let us have a look at the class of an element in its html code. The class attribute value is gsc-input.


1 Answers

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')] 
like image 91
Robin Avatar answered Oct 01 '22 11:10

Robin