Regular expression in xpath


Hi Lakshay,
I would like to know how do we use Regular expression in finding elements using xpath in Selenium Webdriver.
In my current project,one page contains multiple checkbox items with all most similar pattern in xpath,  I am wondering whether can I use xpath instead of creating elements for each of the checkboxes.
One check box xpath is
another checkbox xpath is
another is, html/body/center/div/table/tbody/tr/td/div[2]/form/table[2]/tbody/tr/td[1]/table[2]/tbody/tr/td/table[2]/tbody/tr[16]/td[1]/input

How can I optimize the code by the use of regular expression in xpath without creating elements for each checkboxes.
Your help is really appreciated.


Train Asked on November 17, 2014 in Selenium WebDriver.

Hi Nisha,

Both the solutions are good below by Ankit & Vishal. Please close your question:

Lakshay Sharma

on November 18, 2014.
Add Comment
  • 3 Answer(s)
    Best answer

    Hi Nisha

    Your Xpath For All Elements  Same Except That Row Index

    try Something Like This

    {For(some values of i)
     driver.findElement(by.xpath("html/body/center/div/table/tbody/tr/td/div[2]/form/table[2]/tbody/tr/td[1]/table[2]/tbody/tr/td/table[2]/tbody/tr["+ i +"]/td[1]/input"));    // Replace that Index with some variable
    Vice Professor Answered on November 18, 2014.
    Add Comment

    Hi Nisha,

    If you will observe the pattern then you will find, that the row index is changing. You just need split your xpath as

    StartString= “html/body/center/div/table/tbody/tr/td/div[2]/form/table[2]/tbody/tr/td[1]/table[2]/tbody/tr/td/table[2]/tbody/tr[”
    EndString= “]/td[1]/input”

    xpath= StartString+”index”+EndString

    Here you only pass the value of index, that can be 3, 7, 16 etc.

    Please let me know if there is any gap.

    Train Answered on November 18, 2014.
    Add Comment

    Thank you for your replies

    Train Answered on November 18, 2014.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.