Hugo
Hugo

Reputation: 4104

Find number of characters matching pattern in XSLT 1

I need to make an statement where the test pass if there is just one asterisk in a string from the source document.

Thus, something like

<xslt:if test="count(find('\*', @myAttribute)) = 1)>
    There is one asterisk in myAttribute
</xslt:if>

I need the functionality for XSLT 1, but answers for XSLT 2 will be appreciated as well, but won't get acceptance unless its impossible in XSLT 1.

Upvotes: 2

Views: 2900

Answers (2)

J&#246;rn Horstmann
J&#246;rn Horstmann

Reputation: 34014

Another solution that should work in XPath 1.0:

contains(@myAttribute, '*') and not(contains(substring-after(@myAttribute, '*'), '*')) 

Upvotes: 1

Pavel Minaev
Pavel Minaev

Reputation: 101555

In XPath 1.0, we can do it by removing all asterisks using translate and comparing the length:

string-length(@myAttribute) - string-length(translate(@myAttribute, '*', '')) = 1

In XPath 2.0, I'd probably do this:

count(string-to-codepoints(@myAttribute)[. = string-to-codepoints('*')]) = 1

Upvotes: 4

Related Questions