XML technologies / XSLT / XSLT Cookbook / Exploiting the potential of XSLT 2.0 / Processing unstructured text with regular expressions

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You need to transform XML containing unstructured text into a correctly marked-up document.

Solution

There are three XPath 2.0 functions for regular expressions: match( ), replace( ) and tokenize( ). We covered them in XPath. A new XSLT instruction, xsl:analyze-string, supports even more demanding text-processing tasks.

Instruction xsl:analyze-string takes attribute select specifying the string, attribute regex specifying the regular expression, and optional attribute flags modifying the regex engine’s behavior. The standard flags are:

  • i Case-insensitive mode.

  • m Multiline mode: metacharacters ^ and $ match line beginnings and ends rather than the whole string’s beginning and end, the default.

  • s Makes metacharacter . match newlines (entity 
), normally excluded. Sometimes called single-line mode, this is not the opposite of multiline mode: flags s and m can even be combined.

  • x Allows whitespace in a regex as separators rather than significant characters.

Child element xsl:matching-substring processes the substring matched by the regex; xsl:non-matching-substring handles substrings not matched by the regex. Either child may be omitted. Function regex-group also permits references inside xsl:matching-substring to captured groups, the parenthesized parts of a regular expression:

<xsl:template match="date">
  <xsl:copy>
    <xsl:analyze-string select="normalize-space(.)" regex="(\d\d\d\d) ( / | - ) (\d\d) ( / | - ) (\d\d)" flags="x">
      <xsl:matching-substring>
        <year><xsl:value-of select="regex-group(1)"/></year>
        <month><xsl:value-of select="regex-group(3)"/></month>
        <day><xsl:value-of select="regex-group(5)"/></day>
      </xsl:matching-substring>
      <xsl:non-matching-substring>
        <error><xsl:value-of select="."/></error>
      </xsl:non-matching-substring>
    </xsl:analyze-string>
  </xsl:copy>
</xsl:template>

A useful complement to xsl:analyze-string is XSLT function unparsed-text( ), which reads a text file into a string. As its name suggests, the file is not parsed and need not be XML. Only in very unusual circumstances would you apply unparsed-text( ) to XML content.

This stylesheet converts a simple comma-delimited file without quoted strings into XML:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/02/xpath-functions" xmlns:xdt="http://www.w3.org/2005/02/xpath-datatypes">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
  <xsl:param name="csv-file" select=" 'test.csv' "/>
  <xsl:template match="/">
    <converted-csv filename="{$csv-file}">
      <xsl:for-each select="tokenize(unparsed-text($csv-file, 'UTF-8'),'\n')">
        <xsl:if test="normalize-space(.)">
          <row>
            <xsl:analyze-string select="." regex="," flags="x">
              <xsl:non-matching-substring>
                <col><xsl:value-of select="normalize-space(.)"/></col>
              </xsl:non-matching-substring>
            </xsl:analyze-string>
          </row>
        </xsl:if>
      </xsl:for-each>
    </converted-csv>
  </xsl:template>
</xsl:stylesheet>

Discussion

The regex capabilities of XSLT 2.0 together with unparsed-text( ) enable processing almost impossible in XSLT 1.0. Still, XSLT would not be my first choice for non-XML content unless a multilingual solution, such as Java and XSLT or Perl and XLST, were impractical. If XSLT is the only language you want to master, its new features open new areas to explore.

Part of my hesitation about unstructured-text processing in XSLT comes from the “missing functions” in xsl:analyze-string. It would be useful if functions position( ) and last( ) worked within xsl:matching-substring to identify match number position( ) out of last( ) possible matches. Sometimes I use xsl:for-each over a tokenize( ) instead of xsl:analyze-string, but that is insufficient because it returns only unmatched portions. Complex parsing with many possible regex matches in a regex with alternation ( | ), one often resorts to xsl:analyze-string. Yet identifying which regex matched requires another filter using function match( ), redundant and wasteful in my view, since the regex engine already knows which part matched:

<xsl:template match="text( )">
  <xsl:analyze-string select="." regex='[\-+]?\d\.\d+\s*[eE][\-+]?\d+ | [\-+]?\d+\.\d+ | [\-+]?\d+ | "[^"]*?" ' flags="x">
    <xsl:matching-substring>
      <xsl:choose>
        <xsl:when test="matches(.,'[\-+]?\d\.\d+\s*[eE][\-+]?\d+')">
          <scientific><xsl:value-of select="."/></scientific>
        </xsl:when>
        <xsl:when test="matches(.,'[\-+]?\d+\.\d+')">
          <decimal><xsl:value-of select="."/> </decimal>
        </xsl:when>
        <xsl:when test="matches(.,'[\-+]?\d+')">
          <integer><xsl:value-of select="."/> </integer>
        </xsl:when>
        <xsl:when test='matches(.," "" [^""]*? "" ", "x")'>
          <string><xsl:value-of select="."/></string>
        </xsl:when>
      </xsl:choose>
    </xsl:matching-substring>
  </xsl:analyze-string>
</xsl:template>

Hindsight is easy, and language evolution faces implementation difficulties and tradeoffs. With respect to the XSLT 2.0 committee, it would still be nicer if xsl:analyze-string worked as follows:

<!-- KEIN GÜLTIGES XSLT 2.0 - Wunschtraum des Autors -->
<xsl:template match="text( )">
  <xsl:analyze-string select="." flags="x">
    <xsl:matching-substring regex="[\-+]?\d\.\d+\s*[eE][\-+]?\d+">
      <scientific><xsl:value-of select="."/></scientific>
    </xsl:matching-substring>
    <xsl:matching-substring regex="[\-+]?\d+\.\d+'">
      <decimal><xsl:value-of select="."/> </decimal>
    </xsl:matching-substring>
    <xsl:matching-substring regex=" [\-+]?\d+')">
      <integer><xsl:value-of select="."/> </integer>
    </xsl:matching-substring>
    <xsl:matching-substring regex=' "[^"]*?" '>
      <string><xsl:value-of select="."/></string>
    </xsl:matching-substring>
    <xsl:non=matching-substring>
      <other><xsl:value-of select="."/></other>
    </xsl:non=matching-substring>
  </xsl:analyze-string>
</xsl:template>

  

 

 

 

back to top