XML technologies / XSLT / XSLT Cookbook / Strings / Working without regular expressions

(Excerpt from “XSLT Kochbuch” by Sal Mangano)

Problem

You want to perform Regex-like operations in XSLT 1.0 without resorting to nonstandard extensions.

Solution

Several common regex-style filters can be emulated in native XPath 1.0. The following table lists them using Perl syntax alongside its XSLT/XPath equivalent. The single character “C” stands for a user-specified single character, and string “abc” stands for a user-specified nonempty string.

Table: regex filters.

Perl

XSLT/XPath

$string =~ /^C*$/

translate($string,'C','') = ''

$string =~ /^C+$/

$string and translate($string,'C', '') = ''

$string =~ /C+/

contains($string,'C')

$string =~ /C{2,4}/

contains($string,'CC') and not(contains($string,'CCCCC'))

$string =~ /^abc/

starts-with($string,'abc')

$string =~ /abc$/

substring($string, string-length($string) – string-length('abc') + 1) = 'abc'

$string =~ /abc/

contains($string,'abc')

$string =~ /^[^C]*$/

translate($string,'C','') = $string

$string =~ /^\s+$/

not(normalize-space($string))

$string =~ /\s/

translate(normalize-space($string),' ','') != $string

$string =~ /^\S+$/

translate(normalize-space($string),' ','') = $string

Discussion

For brevity and performance, a good regex engine is hard to beat. However, many simple filtering operations can be emulated by more cumbersome but still effective XPath expressions. Many of these filters are enabled by translate( ), which removes irrelevant characters so the filter can be implemented as an equality test. Another useful application of translate is counting occurrences of a particular character or character set. For example, the following code counts numeric characters in a string:

string-length(translate($string, translate($string,'0123456789',''),''))

If this code is unclear, see recipe Remove specific characters from a string. Alternatively, you can write:

string-length($string) - string-length(translate($string,'0123456789',''))

This code trades a translate( ) call for an additional string-length( ) and a subtraction. It might be slightly faster.

An important difference between these XPath expressions and their Perl counterparts is that Perl sets special variables as a side effect of filtering. These variables enable powerful string-processing techniques beyond XSLT’s scope. If someone tried combining Perl and XSLT into a hybrid language, I would be among the first alpha testers!

The good news is that XPath 2.0 now supports regular expressions. I cover this welcome addition next in recipe Use regular expressions.

  

 

 

 

back to top