XML technologies / XSLT / XSLT Cookbook / Strings / Searching for substrings from the end
(Excerpt from “XSLT Kochbuch” by Sal Mangano)
Problem
XSLT has no functions for searching strings backward.
Using regular expressions
This chapter introduces a favorite tool for complex string manipulation: regular expressions, also called regex, short for regular expressions. Regex support was on almost every XSLT developer’s top-ten wish list. This introduction is for newcomers or those intimidated by regexes. It is not comprehensive, but enough to start.
A regular expression is a string encoding a pattern to match in another string. The simplest pattern is the string itself: regex “foo” matches “foobar” starting at its first character. Real power comes from special metacharacters.
The most important metacharacters construct wildcard patterns.
A dot
(.)matches one character.A character class (
[aeiou],[a-z]or[a-zA-Z]) matches a list, range or combination of both.Common classes have abbreviations. For example,
\sabbreviates whitespace characters, including spaces, tabs, newlines and carriage returns;\dabbreviates[0–9]. Uppercasing a backslash abbreviation often negates its class. For example,\Smatches non-whitespace and\Da non-digit. This is not universal:\nmatches a newline, but\Ndoes not mean non-newline. The same applies to\t(tab) and\r(carriage return).Negate a class by starting it with
^. For example,[^aeiou]matches every character except those lowercase vowels. Ranges work too:[^0–9]is equivalent to\D.Literals and wildcards often mix. For example,
d[aeiou]gmatches “dag”, “deg”, “dig”, “dog”, “dug” and longer strings containing them.Repetition metacharacters match preceding characters, wildcards or groups repeatedly.
Metacharacter
*means zero or more repetitions, sobe*matches strings containing “b”, “be”, “bee”, “beee”, and so on.(10)*matches strings containing “10”, “1010”, “101010”, etc. Parentheses group the pattern; without them,10*repeats only the0.Metacharacter
+means one or more repetitions, sobe+matches “be”, “bee”, “beee”, etc., but not “b”.Metacharacter
?means zero or one occurrence, sobe?matches strings containing “b” and “be”.Pattern position often matters, especially the beginning
(^)or end($)of the string, or anchoring at both ends. “^be+” matches “bee keeper”, not “has been”. “be+$” matches “to be or not to be”, not “be he alive or be he dead”. “be+$” matches “be” and “bee”, not “been” or “Abe”.These patterns cover most searches, but some context-sensitive searches need more. Consider numbers beginning and ending with the same digit, such as 11, 909, 3233. Pure regexes cannot express this; most engines, including XPath 2.0, provide extensions.
Two conventions are needed: parentheses mark the part to reference later as a captured group, then an indexed variable refers to it. For example,
(\d)\d*\1matches numbers beginning and ending with the same digit. The first digit is group(\d ), and reference\1means whatever that group captured. Several groups are possible:(\d)(\d)\1\2matches “1212” and “9999”, but not “1213” or “1221”. Backreferences such as\1,\2and others are used with XPath 2.0 functionmatches(). Similar notation using$instead of\is reserved for references outside the expression, as in functionreplace(), referring from a replacement to captured groups. For example,replace($einText, `(\d)\d*', `$1')replaces the first sequence of one or more digits in$einTextwith its first digit. Instructionxsl:analyze-stringalso supports this. Details appear in recipes Reversing a string and Working without regular expressions.
For more, read Reguläre Ausdrücke by Jeffrey E. F. Friedl (O’Reilly). For the XSLT 2.0 approach, see XPath 2.0 by Michael Kay (Wrox, 2004), or W3C recommendations String Functions that Use Pattern Matching and Regular Expressions.
Solution
XSLT 1.0
Use recursion to emulate reverse searching by finding the last occurrence of substr. This yields a substring-before-last and a substring-after-last:
<xsl:template name="substring-before-last">
<xsl:param name="input" />
<xsl:param name="substr" />
<xsl:if test="$substr and contains($input, $substr)">
<xsl:variable name="temp" select="substring-after($input, $substr)" />
<xsl:value-of select="substring-before($input, $substr)" />
<xsl:if test="contains($temp, $substr)">
<xsl:value-of select="$substr" />
<xsl:call-template name="substring-before-last">
<xsl:with-param name="input" select="$temp" />
<xsl:with-param name="substr" select="$substr" />
</xsl:call-template>
</xsl:if>
</xsl:if>
</xsl:template>
<xsl:template name="substring-after-last">
<xsl:param name="input"/>
<xsl:param name="substr"/>
<!-- Extrahiert den String, der nach dem ersten Vorkommen kommt -->
<xsl:variable name="temp" select="substring-after($input,$substr)"/>
<xsl:choose>
<!-- Falls der Suchstring immer noch enthalten ist, erfolgt rekursive Verarbeitung -->
<xsl:when test="$substr and contains($temp,$substr)">
<xsl:call-template name="substring-after-last">
<xsl:with-param name="input" select="$temp"/>
<xsl:with-param name="substr" select="$substr"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$temp"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>XSLT 2.0
XSLT 2.0 adds no reverse versions of substring-before/after, but versatile function tokenize() uses regular expressions to achieve the effect:
<xsl:function name="ckbk:substring-before-last">
<xsl:param name="input" as="xs:string"/>
<xsl:param name="substr" as="xs:string"/>
<xsl:sequence select="if ($substr) then if (contains($input, $substr)) then string-join(tokenize($input, $substr)[position( ) ne last( )],$substr) else '' else $input"/>
</xsl:function>
<xsl:function name="ckbk:substring-after-last">
<xsl:param name="input" as="xs:string"/>
<xsl:param name="substr" as="xs:string"/>
<xsl:sequence select="if ($substr) then if (contains($input, $substr)) then tokenize($input, $substr)[last( )] else '' else $input"/>
</xsl:function>Both functions must check whether substring is empty because tokenize disallows empty patterns. These implementations still differ from their native equivalents because tokenize treats the second argument as regex, not literal text. Escape regex metacharacters to fix this, optionally controlled by a third boolean argument. Two- and three-argument versions coexist because XSLT identifies functions by name and arity, the argument count:
<xsl:function name="ckbk:substring-before-last">
<xsl:param name="input" as="xs:string"/>
<xsl:param name="substr" as="xs:string"/>
<xsl:param name="mask-regex" as="xs:boolean"/>
<xsl:variable name="matchstr" select="if ($mask-regex) then replace($substr,'([.+?*^$])','\$1') else $substr"/>
<xsl:sequence select="ckbk:substring-before-last($input,$matchstr)"/>
</xsl:function>
<xsl:function name="ckbk:substring-after-last">
<xsl:param name="input" as="xs:string"/>
<xsl:param name="substr" as="xs:string"/>
<xsl:param name="mask-regex" as="xs:boolean"/>
<xsl:variable name="matchstr" select="if ($mask-regex) then replace($substr,'([.+?*^$])','\$1') else $substr"/>
<xsl:sequence select="ckbk:substring-after-last($input,$matchstr)"/>
</xsl:function>Discussion
Both string search functions (substring-before and substring-after) start at the beginning. To search backward, repeatedly apply them recursively until the final occurrence is found.
Warning!
My first implementation had a trap common to recursive string templates: remember that contains($irgendwas, '') always returns true. Therefore I check for a nonempty $substr value in recursive calls to substring-before-last and substring-after-last. Without these tests, empty inputs cause an infinite loop or stack overflow without tail-call optimization.
Another algorithm is divide and conquer. Split the string in half. If the search string is in the second half, discard the first and recurse on a problem half the size. The tricky case is a match spanning both halves. Here is a solution for substring-before-last:
<xsl:template name="str:substring-before-last">
<xsl:param name="input"/>
<xsl:param name="substr"/>
<xsl:variable name="mid" select="ceiling(string-length($input) div 2)"/>
<xsl:variable name="temp1" select="substring($input,1, $mid)"/>
<xsl:variable name="temp2" select="substring($input,$mid +1)"/>
<xsl:choose>
<xsl:when test="$temp2 and contains($temp2,$substr)">
<!-- Suchstring ist in der zweiten Hälfte, die erste Hälfte wird also einfach angehängt, auf der zweiten Hälfte wird rekursiv fortgefahren -->
<xsl:value-of select="$temp1"/>
<xsl:call-template name="str:substring-before-last">
<xsl:with-param name="input" select="$temp2"/>
<xsl:with-param name="substr" select="$substr"/>
</xsl:call-template>
</xsl:when>
<!--Suchstring befindet sich in den Grenzen, ein einfaches substring-before reicht daher-->
<xsl:when test="contains(substring($input, $mid - string-length($substr) +1), $substr)">
<xsl:value-of select="substring-before($input,$substr)"/>
</xsl:when>
<!--Suchstring befindet sich in der ersten Hälfte, die zweite wird daher einfach weggeworfen-->
<xsl:when test="contains($temp1,$substr)">
<xsl:call-template name="str:substring-before-last">
<xsl:with-param name="input" select="$temp1"/>
<xsl:with-param name="substr" select="$substr"/>
</xsl:call-template>
</xsl:when>
<!-- Kein Auftreten des Suchstrings, wir sind fertig -->
<xsl:otherwise/>
</xsl:choose>
</xsl:template>It turns out that divide and conquer helps little unless the text is large, around 4,000 characters or more. A wrapper template could choose an algorithm by length or switch from divide and conquer to the simpler algorithm once the remaining piece is small.
Copyright © 2006 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “XSLT Kochbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O'Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de