How to construct a dynamic xpath with regex pattern



  • Pattern --> sometext + '(' + F|R|O|H|C + ')'

    String toolTipTextLabel = driver.findElement(By.xpath("//span[contains(@class,'chartTooltip-label')]/descendant::bdi[contains(text(),'(F|R|O|H|C)')]")).getText();  
    


  • Xpath 1.0 does not support regular expressions.

    XPath 2.0 supports regular expression by using matches() function:

    Your example: /descendant::bdi[contains(matches(),'(F|R|O|H|C)')]")

    If you can't use Xpath 2.0 (and you probably can't because browsers don't support this) I would go with something like this:

    String toolTipTextLabel;
    
    List<WebElement> toolTipTextElement = driver.findElements(By.xpath("//span[contains(@class,'chartTooltip-label')]/descendant::bdi"));
    
    for (WebElement e : toolTipTextElements) {
       if (e.getText().matches("(F|R|O|H|C)")) {
          toolTipTextLabel = e.getText();
       }
    }
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2