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 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.
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