Subexpressions
It’s often useful to split a regular expression into
subexpressions. A subexpression is surrounded by parentheses, and can be
modified by a quantifier to define how often (or if) an expression can
occur. For example, this regular expression matches a phone number in
the format 999-999-9999:
([0-9]{3})-([0-9]{3})-([0-9]{4})The regular expression has three subexpressions, each of which
matches a group of digits. XSLT 2.0 provides the regex-group() function to retrieve the part of the analyzed string that matches
a particular subexpression. Here’s an example:
<?xml version="1.0" encoding="utf-8"?> <!-- subexpressions1.xsl --> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="/"> <xsl:analyze-string select="'Call me at 919-555-1212, please.'" regex="([0-9]{{3}})-(\p{{Nd}}{{3}})-([0-9]{{4}})"> <xsl:matching-substring> <xsl:text>The matching substring is '</xsl:text> <!-- <xsl:value-of select=”."/> does the same thing here --> <xsl:value-of select="regex-group(0)"/> <xsl:text>'
</xsl:text> <xsl:text>The formatted string is '</xsl:text> <xsl:value-of select="('(', regex-group(1), ') ', regex-group(2), '-', regex-group(3), '''')" separator=""/> </xsl:matching-substring> </xsl:analyze-string> </xsl:template> </xsl:stylesheet>
(The curly braces in this example are doubled so that the XSLT processor knows this is not an attribute value template.) Notice that the regular expression contains two ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access