Hannah
Hannah

Reputation: 27

XPath of element containing N number of a certain character?

I want the XPath of an element whose @id contains 3 hyphens.

e.g. I want to select the second element below

<a id="X-X"></a>
<a id="X-X-X-X"></a>
<a id="X-X-X"></a>

Upvotes: 1

Views: 562

Answers (1)

kjhughes
kjhughes

Reputation: 111541

XPath 2.0

This XPath 2.0 expression,

//a[matches(@id, "^([^-]*-){3}[^-]*$")]

will select all a elements with id attributes that have 3 - characters in its value. It can easily be adapted to count characters other than - or to require certain characters to be between the - characters.

XPath 1.0

This XPath 1.0 expression,

//a[string-length(@id) - string-length(translate(@id,"-","")) = 3]

will select all a elements with id attributes that have 3 - characters in its value.

Upvotes: 1

Related Questions