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?
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.
The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]
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.
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.
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With