Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a Regex in an XPath expression?

Something like .//div[@id='foo\d+] to capture div tags with id='foo123'.

I'm using .NET, if that matters.

like image 487
ripper234 Avatar asked Jan 01 '09 15:01

ripper234


People also ask

Is XPath a regex?

The XPath regex plugin is used to match style which contains one or more values unique from attributes and elements in our xml documents. XPath regex is helped us using locate the part of an attribute which stays consistent for identifying the element of the web in a web page.

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.

What is XPath regular expression?

A Regular Expression in Xpath helps with using part of a locator attribute that stays constant to identify a web element on a web page. Because some times the values within the HTML code for the attributes change. For instance attributes would change every time the web page you are working on is refreshed.

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

As other answers have noted, XPath 1.0 does not support regular expressions.

Nonetheless, you have the following options:

  • Use an XPath 1.0 expression (note the starts-with() and translate() functions) like this:
 .//div    [starts-with(@id, 'foo')    and     'foo' = translate(@id, '0123456789', '')   and    string-length(@id) > 3       ] 
  • Use EXSLT.NET -- there is a way to use its functions directly in XPath expressions without having to use XSLT. The EXSLT extension functions that allow RegEx-es to be used are: regexp:match(), regexp:replace() and regexp:test()

  • Use XPath 2.0/XSLT 2.0 and its inbuilt support for regular expressions (the functions matches(), replace() and tokenize())

like image 89
Dimitre Novatchev Avatar answered Sep 25 '22 11:09

Dimitre Novatchev