0

I use Selenium 2.35.0, latest Firefox, and Linux OS.

I unable to use regular expression in my java application.

I have a line like this:

Iterator<WebElement> iterator =
driver.findElements(By.xpath("//a[matches(@href, 'site.ru/[0-9]*/')]")).iterator();

Exception occured:

org.openqa.selenium.InvalidSelectorException: The given selector //a[matches(@href, "site.ru/[0-9]/")] is either invalid or does not result in a WebElement. The following error occurred: InvalidSelectorError: Unable to locate an element with the xpath expression //a[matches(@href, "site.ru/[0-9]/")]

Could you please help me with investigation reason of this fault?

2
  • maybe you need match all href text like this .*site.ru/[0-9]*/.* Commented Oct 5, 2013 at 10:16
  • @Darka, good thought, but the XPath matches() function already matches if the regex exists anywhere in the string. Commented Oct 5, 2013 at 13:49

1 Answer 1

1

It'd be better to see your real input, or a portion of which that shows the problem, but perhaps this'll help.

//a[matches(@href, 'site.ru/[0-9]*/')]

against these links:

<html>
  <div>
    <a href="site.ru//">Link 1</a>
    <a href="site.ru/123/">Link 2</a>
    <a href="http://site.ru/123/">Link 3</a>
    <a href="site.ru/">Link 4</a>
    <a href="site.ru/123">Link 5</a>
    <a href="site.ru/abc/123">Link 6</a>
  </div>
</html>

will match Links 1-3 but not 4-6.

If you need to match 4-6 too, you could drop the trailing slash in the regex:

//a[matches(@href, 'site.ru/[0-9]*')]

If this is too liberal and picks up cases you do not want to match, then comment below on which specific cases must be excluded, and we'll try to adjust accordingly.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to match Links 1-3 only, but it is does not work (see exception in the initial problem description).
Given that the XPath is correct, consider that input may not contain what we think it does. Suggest you post actual input. Second choice would be to broaden XPath and see if we can select any unqualified a as a sanity check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.