2

I would like to loop and find elements starting with a string and ends with a digit but I'm not sure how to do it with ends-with()

I have this code here

*[starts-with(name(), 'cup') and ends-with(name(), '_number')]

ps: not sure what version of xpath the application is using

Jonathan
  • 2,700
  • 4
  • 23
  • 41

2 Answers2

2

XPath 2.0

This is straight-forward in XPath 2.0, where this expression,

//*[matches(name(), '^cup.*\d$')]

will select all elements whose name starts with cup and ends with a digit, as requested.

XPath 1.0

Since XPath 1.0 lacks regex, ends-with(), and functions to test if a string is a numbers, your request gets to be more complicated with XPath 1.0. Here's one possible working solution:

//*[starts-with(name(), 'cup') 
    and number(substring(name(),string-length(name()))) 
      = number(substring(name(),string-length(name())))]

Note that the second clause is a clever way by Dimitre Novatchev to test in XPath 1.0 whether a string is a number.

Here's a shorter way to check for ending in a digit in XPath 1.0:

//*[starts-with(name(), 'cup') 
    and not(translate(substring(name(),string-length(name())), '0123456789', ''))]
kjhughes
  • 106,133
  • 27
  • 181
  • 240
1

I believe ends-with is not in Xpath 1.0 , you must be using atleast XPath 2.0 , then you can use matches() to match string with digit at end like:

matches(name(), '.*\d+$')

`then xpath will be :

*[starts-with(name(), 'cup') and matches(name(), '.*\d+$')] or just like as @kjhughes mentioned in his answer :

*[matches(name(), '^cup.*\d+$')]

SomeDude
  • 13,876
  • 5
  • 21
  • 44