Re: [xsl] Move leading/trailing spaces outside (XSLT 2.0)

Subject: Re: [xsl] Move leading/trailing spaces outside (XSLT 2.0)
From: Abel Braaksma <>
Date: Tue, 06 Feb 2007 17:27:27 +0100
Michael Kay wrote:
<xsl:template match="e">
<xsl:analyze-string select="." regex="^\s*.*?\s*$">
I think that needs to be
<xsl:analyze-string select="." regex="^(\s*)(.+?)(\s*)$"> as the posted regular expression lacks parentheses to allow the later use of regex-group and as the posted regular expression matches the empty string which is not allowed.

Quite right, thanks.


Please note the subtle differences between the above mentioned solution and the one I proposed. Both have their pros and cons. Depending on your final needs, one or the other may suit you best. Using

<xsl:analyze-string select="." regex="^(\s*)(.+?)(\s*)$">

will match the total string, so no need for using non-matching-substring. This has the advantage that you can do string-manipulation on the whole match at once, using regex-group(1), (2) and (3). If you only do string-replacement, your can optimize this with the replace() function.


<xsl:analyze-string select="." regex="^\s+|\s+$">

is quicker, has the advantage of separating logic, but has the disadvantage that you cannot intermix the matching and non-matching strings (meaning, when you are in non-matching-substring, it contains the non-space content of your match, and you cannot get the matching-substring from that instruction and vice versa).

If you need to create a node where the match is part of a childnode of the non-match, of vv, use the first solution with regex-group, if the nodes are siblings, you can use either (whichever you find clearest), if the nodes are only text-nodes, you can use replace() instead, depending a bit on the complexity of the match. If you mix text with nodes (mixed content), it depends a bit (but you cannot use replace()).

-- Abel

Current Thread