matching-substring : analyze string « XSLT stylesheet « XML






matching-substring


File: Data.xml

<?xml version="1.0" encoding="utf-8"?>
<phonelist>
  <phonenumber>111-111-1111</phonenumber>
  <phonenumber>(111) 111-1111</phonenumber>
  <phonenumber>111.111.1111</phonenumber>
  <phonenumber>111-111-1111</phonenumber>
  <phonenumber>+11 111-1111</phonenumber>
</phonelist>

File: Transform.xslt

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:for-each select="phonelist/phonenumber">
      <xsl:analyze-string select="." 
        regex="([0-9]{{3}})(-|\.)([0-9]{{3}})(-|\.)([0-9]{{4}})">
        <xsl:matching-substring>
          <xsl:text>&#xA;+1 (</xsl:text>
          <xsl:value-of select="regex-group(1)"/>
          <xsl:text>) </xsl:text>
          <xsl:value-of select="regex-group(3)"/>
          <xsl:text>-</xsl:text>
          <xsl:value-of select="regex-group(5)"/>
        </xsl:matching-substring>
        <xsl:non-matching-substring>
          <xsl:text>&#xA;   Unrecognized phone number: </xsl:text>
          <xsl:value-of select="."/>
        </xsl:non-matching-substring>
      </xsl:analyze-string>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

Output:


+1 (111) 111-1111
   Unrecognized phone number: (111) 111-1111
+1 (111) 111-1111
+1 (111) 111-1111
   Unrecognized phone number: +11 111-1111
   

 








Related examples in the same category

1.analyze-string and regular expression
2.non-matching-substring and matching-substring