XML technologies / XSLT / XSLT Cookbook / Strings / Replacing text

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You want to replace every occurrence of a substring in a target string with another string.

Solution

XSLT 1.0

The following recursive template replaces every occurrence of a search string with a replacement:

<xsl:template name="search-and-replace">
  <xsl:param name="input"/>
  <xsl:param name="search-string"/>
  <xsl:param name="replace-string"/>
  <xsl:choose>
    <!-- Feststellen, ob die Eingabe den Suchstring enthält -->
    <xsl:when test="$search-string and contains($input,$search-string)">
      <!-- Ist dies der Fall, dann Verkettung des Teilstrings vor dem Suchstring mit dem Ersatzstring und mit dem Ergebnis der rekursiven Anwendung dieses Templates mit dem verbleibenden Teilstring. -->
      <xsl:value-of select="substring-before($input,$search-string)"/>
      <xsl:value-of select="$replace-string"/>
      <xsl:call-template name="search-and-replace">
        <xsl:with-param name="input" select="substring-after($input,$search-string)"/>
        <xsl:with-param name="search-string" select="$search-string"/>
        <xsl:with-param name="replace-string" select="$replace-string"/>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <!-- Keine weiteren Vorkommen des Suchstrings, daher einfach Rückgabe des aktuellen Eingabestrings -->
      <xsl:value-of select="$input"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

To replace only whole words, characters immediately before and after the match must belong to the word-separator class. We declare the characters in variable $punc and whitespace to be word separators:

<xsl:template name="search-and-replace-whole-words-only">
  <xsl:param name="input"/>
  <xsl:param name="search-string"/>
  <xsl:param name="replace-string"/>
  <xsl:variable name="punc" select="concat('.,;:( )[  ]!?$@&amp;&quot;',&quot;'&quot;)"/>
  <xsl:choose>
    <!-- Feststellen, ob die Eingabe den Suchstring enthält -->
    <xsl:when test="contains($input,$search-string)">
      <!-- Ist dies der Fall, dann testen, ob das vorherige und das folgende Zeichen Worttrennzeichen sind. -->
      <xsl:variable name="before" select="substring-before($input,$search-string)"/>
      <xsl:variable name="before-char" select="substring(concat(' ',$before),string-length($before) +1, 1)"/>
      <xsl:variable name="after" select="substring-after($input,$search-string)"/>
      <xsl:variable name="after-char" select="substring($after,1,1)"/>
      <xsl:value-of select="$before"/>
      <xsl:choose>
        <xsl:when test="(not(normalize-space($before-char)) or contains($punc,$before-char)) and (not(normalize-space($after-char)) or contains($punc,$after-char))">
          <xsl:value-of select="$replace-string"/>
        </xsl:when>
        <xsl:otherwise>
          <xsl:value-of select="$search-string"/>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:call-template name="search-and-replace-whole-words-only">
        <xsl:with-param name="input" select="$after"/>
        <xsl:with-param name="search-string" select="$search-string"/>
        <xsl:with-param name="replace-string" select="$replace-string"/>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <!-- Es gibt keine weiteren Vorkommen des Suchstrings, daher einfach Rückgabe des aktuellen Eingabestrings -->
      <xsl:value-of select="$input"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Note:
Notice how $punc is constructed with concat( ) to contain both single and double quotation marks. There is no other way, since XPath and XSLT, unlike C, cannot escape special characters with a backslash (\). XPath 2.0 allows quotation marks to be escaped by doubling them.

XSLT 2.0

The functionality of search-and-replace is built into the 2.0 function replace(). The functionality of search-and-replace-whole-words-only is easily emulated with a regular expression matching words:

<xsl:function name="ckbk:search-and-replace-whole-words-only">
  <xsl:param name="input" as="xs:string"/>
  <xsl:param name="search-string" as="xs:string"/>
  <xsl:param name="replace-string" as="xs:string"/>
  <xsl:sequence select="replace($input, concat('(^|\W)',$search-string,'(\W|$)'), concat('$1',$replace-string,'$2'))"/>
</xsl:function>

Caution!
Many regex engines use \b for word boundaries, but XPath 2.0 does not support it.

Here we construct a regular expression by surrounding $search-string with (^|\W) and (\W|$), where \W means “not \w” or “nonword character”. The characters ^ and $ handle a word at the start or end of the string. The matched \W character must also be put back in the text, using references to captured groups $1 and $2.

The function replace() is more powerful than these XSLT 1.0 solutions because it uses regular expressions and remembers parts of matches. The replacement accesses them through variables $1, $2 and so on. We examine replace() further in the recipe Doing without regular expressions.

Discussion

The task of search and replace is common in text processing. This is the simplest implementation written purely in XSLT. It may seem inefficient: for every occurrence of the search string, it calls contains(), substring-before() and substring-after(). Each probably searches the input again. This appears to perform two unnecessary searches. After some thought, you might suggest one of the next two apparently more efficient solutions.

Example: A temporary string in an unsuccessful attempt to improve search and replace.

<xsl:template name="search-and-replace">
  <xsl:param name="input"/>
  <xsl:param name="search-string"/>
  <xsl:param name="replace-string"/>
  <!-- Sucht den Teilstring vor dem Suchstring und speichert ihn in einer Variablen -->
  <xsl:variable name="temp" select="substring-before($input,$search-string)"/>
  <xsl:choose>
    <!-- Wenn $temp nicht leer ist oder die Eingabe mit dem Suchstring beginnt, dann wissen wir, dass wir eine Ersetzung vornehmen müssen. Damit wird die Notwendigkeit eliminiert, contains( ) zu verwenden. -->
    <xsl:when test="$temp or starts-with($input,$search-string)">
      <xsl:value-of select="concat($temp,$replace-string)"/>
      <xsl:call-template name="search-and-replace">
        <!-- Wir eliminieren die Notwendigkeit, substring-after aufzurufen, indem wir die Länge von temp und den Suchstring verwenden, um den verbleibenden String in dem rekursiven Aufruf zu extrahieren. -->
        <xsl:with-param name="input" select="substring($input,string-length($temp)+ string-length($search-string)+1)"/>
        <xsl:with-param name="search-string" select="$search-string"/>
        <xsl:with-param name="replace-string" select="$replace-string"/>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$input"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Example: A temporary integer in an unsuccessful attempt to improve search and replace.

<xsl:template name="search-and-replace">
  <xsl:param name="input"/>
  <xsl:param name="search-string"/>
  <xsl:param name="replace-string"/>
  <!-- Ermittelt die Länge des Teilstrings vor dem Suchstring und speichert sie in einer Variablen -->
  <xsl:variable name="temp" select="string-length(substring-before($input,$search-string))"/>
  <xsl:choose>
    <!-- Wenn $temp nicht 0 ist oder die Eingabe mit dem Suchstring beginnt, dann wissen wir, dass wir eine Ersetzung vornehmen müssen. Dies eleminiert die Notwendigkeit, contains( ) zu verwenden. -->
    <xsl:when test="$temp or starts-with($input,$search-string)">
      <xsl:value-of select="substring($input,1,$temp)"/>
      <xsl:value-of select="$replace-string"/>
      <!-- Wir eliminieren die Notwendigkeit, substring-after aufzurufen, indem wir temp und die Länge des Suchstrings verwenden, um den verbleibenden String in dem rekursiven Aufruf zu extrahieren. -->
      <xsl:call-template name="search-and-replace">
        <xsl:with-param name="input" select="substring($input,$temp + string-length($search-string)+1)"/>
        <xsl:with-param name="search-string" select="$search-string"/>
        <xsl:with-param name="replace-string" select="$replace-string"/>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$input"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Both attempts share an idea: remember where substring-before( ) finds a match, then use this to avoid calling contains( ) and substring-after( ). You must introduce a call to starts-with( ) to handle cases where substring-before( ) returns an empty string: either no match or a match at the start. However, starts-with( ) is probably faster than contains( ) because it need not search beyond the match length. The second attempt differs by assuming an integer may be cheaper to store than the entire substring.

Unfortunately, these supposed optimisations do not improve performance in the Xalan XSLT implementation and, for some inputs, are an order of magnitude slower than Saxon or XT! My first hypothesis was that variable $temp in the recursive call interfered with Saxon’s tail-call optimisation (see recipe Reversing a string). Yet even large inputs with many matches caused no stack overflow. I next suspected that XSLT’s substring( ) might somehow be slower than calls to substring-before( ) and substring-after( ). Michael Kay, Saxon’s author, explained that its implementation of substring( ) is slow because of the complex rules XSLT’s substring must implement: floating-point argument rounding, special cases with endpoints outside string bounds, and issues with Unicode surrogate pairs. By contrast, substring-before( ) and substring-after( ) map more directly to Java.

The real lesson is that optimisation is complicated, especially in XSLT, where implementations differ greatly and new versions keep adding optimisations. Unless you are profiling, stick with simple solutions. Obvious solutions are also more likely to behave consistently across implementations.

  

 

 

 

back to top