mo-ta-to
mo-ta-to

Reputation: 246

Selenium: is there a way to write an xpath to get elements that contains text that ends with numbers

I'm trying to write an xpath that selects all the elements that contains text which ends with numbers and surrounded by braces. The numbers can be anything and it can be of any number of digits. Is this possible in XPath1.0? I cannot use regex as it is not allowed in XPath1.0

<div class = '12345' >
   <div class = '98231'>I want this (101)</div>
   <div class = '98232'>I don't want this 101</div>
   <div class = '98233'>I want this (1)</div>
   <div class = '98234'>I don't want this (10A1)</div>
</div>

Upvotes: 1

Views: 1008

Answers (2)

frianH
frianH

Reputation: 7563

Try following xpath:

//div//div[text() and contains(text(),'(') and contains(text(),')')]

Upvotes: 0

zx485
zx485

Reputation: 29022

In XPath-1.0 you cannot use RegEx'es.
But you can use the fn:number() function to check if a given string could be a valid number with the fn:boolean function:

/div/div[boolean(number(substring-before(substring-after(.,'('),')')))]

Obviously, this does only work if there are no other brackets in the string. And it doesn't check if the number in brackets is at the end of the string. To add this further restriction, change the expression to

/div/div[not(boolean(string(normalize-space(substring-after(.,')'))))) and boolean(number(substring-before(substring-after(.,'('),')')))]

This adds a further predicate to check if there are characters other than whitespace after the ). Leading and trailing whitespace between the brackets is automatically removed by the fn:number() function.

Upvotes: 2

Related Questions