2

I'm trying to write an xpath such that only nodes with text with numbers alone will be returned. I wanted to use regex and was hoping this would work

td[matches(text(),'[\d.]')]

Can anyone please help me understand what am I doing wrong here

<tr>
        <td>1</td>
        <td>10</td>
        <td>a</td>
</tr>
bsk
  • 196
  • 1
  • 7

3 Answers3

2

seams that you are missing quantification, [\d.] will match only 1 character, so 1 should be selected, 10 on the other site requires something like +, so try your regex like: td[matches(text(),'\d+')]

Also that . in regex will make it capture non-digit characters, do not add that one.

You can test all your regex queries on regex101.

Dusan Gligoric
  • 582
  • 3
  • 21
  • `.` will match any character except line breaks. So `10` will be also selected. But you are right, it is better to use `+` in this case – Andrei Suvorkov Jul 16 '18 at 19:27
  • @AndreiSuvorkov: Should not as its enclosed in square brackets, it will select only 1 character of given set of characters and meta characters in it. – Dusan Gligoric Jul 16 '18 at 19:28
2

AFAIK so far Selenium support XPath 1.0 only, so matches() is not supported.

You can try below instead:

//td[number(.) >= 0 or number(.) < 0]

To match table cells with integers

Andersson
  • 51,635
  • 17
  • 77
  • 129
1

Replace:

td[matches(text(),'[\d+]')]

with:

td[matches(text(),'\d+')]

Note: regex works only in xPath 2.0

Andrei Suvorkov
  • 5,559
  • 5
  • 22
  • 48