June 2008
Intermediate to advanced
986 pages
27h 8m
English
A back-reference allows you to refer to a previously
matched subexpression within the regular expression
itself. As an example, say you want to find words that begin
and end with the same two letters. The expression ([a-z]{2})(.*)\1 does the trick. The \1 represents whatever two characters matched
the first subexpression. The back-reference \2 represents the match for the second
subexpression, \3 represents the
match for the third subexpression, and so on. (Notice that although the
references go backwards, counting subexpressions goes from left to
right.)
Here’s a sample stylesheet:
<?xml version="1.0" encoding="utf-8"?> <!-- back-reference.xsl --> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:text>Using back-references to find words that begin 
</xsl:text> <xsl:text> and end with the same two letters:

</xsl:text> <xsl:text> replace($x, '([a-z]{2})(.*)\1', '$1--$2--$1')
</xsl:text> <xsl:text> edited: </xsl:text> <xsl:value-of select="replace('edited', '([a-z]{2})(.*)\1', '$1--$2--$1')"/> <xsl:text>
 editor: </xsl:text> <xsl:value-of select="replace('editor', '([a-z]{2})(.*)\1', '$1--$2--$1')"/> <xsl:text>
 educated: </xsl:text> <xsl:value-of select="replace('educated', '([a-z]{2})(.*)\1', '$1--$2--$1')"/> <xsl:text>
 orator: </xsl:text> <xsl:value-of select="replace('orator', '([a-z]{2})(.*)\1', '$1--$2--$1')"/> </xsl:template> </xsl:stylesheet> ...
Read now
Unlock full access