Making Do Without Regular Expressions
Problem
You would like to perform regular-expression-like operations but you don’t want to resort to nonstandard extensions.
Solution
Several common regular-expression-like matches can be emulated in native XSLT. Table 1-1 lists the regular-expression matches by using Perl syntax along with their XSLT/XPath equivalent. The single character “C” is a proxy for any user-specified single character, and the string “abc” is a proxy for any user supplied-string of nonzero length.
Table 1-1. Regular-expression matches
$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
When it comes to brevity and power, nothing beats a good
regular-expression engine. However, many simple matching operations
can be emulated by more cumbersome yet effective XPath expressions.
Many of these matches are facilitated by translate( ), which removes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access