XML technologies / XSLT / Reference: XSLT 1.0 and 2.0 elements / analyze-string

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 6.)

A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z

 

The instruction xsl:analyze-string introduced in XSLT 2.0 analyzes strings in the source document using regular expressions.

Classification

Instruction

Function group

Testing string values

Introduced in

XSLT 2.0

Stylesheet position and permitted contents:

The instruction xsl:analyze-string occurs within template bodies.

It contains, in this order, zero or one xsl:matching-substring and xsl:non-matching-substring element. However, one of these subinstructions must be present: omitting one makes the other mandatory. Any number of xsl:fallback elements may also appear. (Note: An XSLT 2.0 processor ignores a fallback instruction here, but it may matter to an XSLT 1.0 processor in forwards-compatible mode.)

Attributes:

All standard attributes are allowed. In addition, xsl:analyze-string has three specific attributes: mandatory select and regex and optional flags.

flags

Value

flag string (also as an AVT)

Usage

Optional

Introduced in

XSLT 2.0

Optional flags control the regular expression’s behavior. Their conventions resemble those of Perl. Flags are strings consisting of m, i, s, x or meaningful combinations of these letters.

The value of attribute flags may be computed dynamically using an attribute value template. A value not composed of one or more permitted flag letters is an error.

  • flags="m"
    Enables multiline mode (multiline). Mode m recognizes line breaks from #x0A newline characters. Without m, string mode applies (Note: This is not the dot-all mode enabled by flag s!). Internal line breaks receive no special treatment; only the whole string’s beginning (^) and end ($) are boundaries by default. With m, ^ additionally matches each line beginning, immediately after a newline, and $ each line end, immediately before a newline.

  • flags="i"
    Disables case sensitivity (case insensitive). Without this flag, two characters are equal only when their Unicode codepoints match (default). With it, characters are equal if Unicode Case Mappings gives a canonical caseless match. (Note: Case folding achieves this. For example, Greek Σ and ς are treated as a match.)

  • flags="x"
    Disables consideration of whitespace characters in the expression. Without it, whitespace is part of the expression and participates in matching (default). With it, line breaks can make long expressions more readable.

  • flags="s"
    Enables dot-all mode, corresponding to Perl’s “single-line” mode. It changes the behavior of the “.” metacharacter (dot). Without s, it matches any character, including whitespace, except newline #x0A (default). With s, it matches every character including newline.

Pitfall – Recognizing a newline as a word boundary:
When a single newline separates two words without an intervening space, only dot-all mode recognizes it as a character between the words.

regex

Value

regular expression (also as an AVT)

Usage

Mandatory

Introduced in

XSLT 2.0

The attribute regex contains a regular expression (regular expression) used to test the string. It may be inserted as an attribute value template. It is an error if the resulting expression matches the empty string.

select

Value

xpath-expression

Usage

Mandatory

Introduced in

XSLT 2.0

The attribute select takes an XPath expression selecting the string to test.

Use:

The instruction xsl:analyze-string takes an input string equal to the string value of the XPath expression in attribute select. Attribute regex contains a regular-expression pattern. At matching positions, the input is split into a sequence of substrings of type xs:string arranged in an output sequence.

If several positions match, the first match is selected. Scanning resumes at the first character after the matched substring.

The expression uses syntax familiar from Perl. The usual metacharacters listed below apply.

Metacharacter

Description

.

The dot represents any character, including newline (#x0A), unless flag m is explicitly specified.

^

A leading caret matches the string beginning, or line beginning with m; it also negates character lists.

$

A trailing dollar sign matches the string end, or line end with m.

|

The pipe means “or”, choosing between characters or groups.

+ (greedy)
+? (non-greedy)

Quantifier;
the preceding character occurs one or more times;
a trailing question mark makes the quantifier non-greedy.

* (greedy)
*? (non-greedy)

Quantifier;
the preceding character occurs zero or more times; a trailing question mark makes it non-greedy.

? (greedy)
?? (non-greedy)

Quantifier;
the preceding character occurs zero or one time;
a trailing question mark makes the quantifier non-greedy.

{n}

Numeric quantifier;
the preceding character occurs exactly n times.

{n,}

Numeric quantifier;
the preceding character occurs at least n times.

{n, m}

Numeric quantifier;
the preceding character occurs at least n and at most m times.

( )

Parentheses form subgroups for backreferences within the pattern, accessible using function regex-group().

[]

Square brackets specify character lists or classes.

Table: Metacharacters in XPath regular expressions. 

Pitfall – Regular expressions in attribute value templates:

An important detail concerns numeric quantifiers {n, m}. Since attribute regex permits attribute value templates, literal braces must be doubled, including within the regular expression.

This expression describes one to three arbitrary characters (dot '.', followed by a numeric quantifier in braces) and a space:

.{1, 3}\s

Within attribute regex it therefore needs doubled braces:

regex=".{{1, 3}}\s" 

Building the sequence:

If no match starts the string, the first substring contains all characters before the first match, excluding the match. The second substring is the match itself. A third would be another non-matching part, and so on.

If input starts with a match, the sequence’s first item is matching, the second non-matching, and so on.

If the entire input matches, or no part matches, exactly one substring contains the entire input and is respectively matching or non-matching.

Empty substrings must never be created. Empty input therefore produces no output sequence, and neither instruction xsl:matching-subst­ring nor xsl:non-matching-substring runs. 

Processing the sequence:

For a nonempty sequence, substrings pass in order to instructions xsl:matching-substring and xsl:non-matching-substring, whose sequence constructors or template blocks run. A missing instruction behaves as if present with an empty body. If both are missing, this is a static error (ERR XTSE1130).

Each processed substring becomes the context item, its sequence position the context position, and the number of substrings the context size.

Examples:

Example 1 – Replace newlines \n with HTML <br>:

<xsl:analyze-string select="abschnitt" regex="\n">
  <xsl:matching-substring>
    <br/>
  </xsl:matching-substring>
  <xsl:non-matching-substring>
    <xsl:value-of select="."/>
  </xsl:non-matching-substring>
</xsl:analyze-string>

The regular expression "\n" matches a newline. The string value of a <abschnitt> container is analyzed. Instruction xsl:non-matching-substring receives the non-matching input portions, all characters except newlines, and outputs them. Upon finding a newline, instruction xsl:matching-substring writes an HTML break. The matching substring, the original newline, is discarded rather than passed on.

Example 2 – Replace a string in prose:

Source document:

<?xml version="1.0" encoding="ISO-8859-1"?>
<beispieltext>Jazzbassisten gibt es wie Sand am Meer. Jazzbassisten, die ehemals Gitarristen waren, und deren Spiel dadurch hörbar geprägt ist, sind schon seltener.</beispieltext>

Each occurrence of “Jazzbassist” is to be replaced with “Violinist”.

Stylesheet:

<xsl:template match="/">
  <ausgabe>
    <xsl:call-template name="substring-ersetzen">
      <xsl:with-param name="suchstring" select="'Jazzbassist'"/>
      <xsl:with-param name="ersetzungsstring" select="'Violinist'"/>
    </xsl:call-template>
  </ausgabe>
</xsl:template>
<xsl:template name="substring-ersetzen">
  <xsl:param name="suchstring"/>
  <xsl:param name="ersetzungsstring"/>
  <xsl:analyze-string regex="{$suchstring}" select="beispieltext">
    <xsl:matching-substring>
      <xsl:value-of select="$ersetzungsstring"/>
    </xsl:matching-substring>
    <xsl:non-matching-substring>
      <xsl:value-of select="."/>
    </xsl:non-matching-substring>
  </xsl:analyze-string>
</xsl:template>

A named template is not essential here, but allows external parameterization of replacement. A stylesheet function could implement a similar solution.

Result:

<?xml version="1.0" encoding="UTF-8"?>
<ausgabe>Violinisten gibt es wie Sand am Meer. Violinisten, die ehemals Gitarristen waren, und deren Spiel dadurch hörbar geprägt ist, sind schon seltener.</ausgabe>

One string in text must be replaced with another. This uses xsl:analyse-string inside a named template. Search and replacement strings are parameters. Note attribute regex, which receives the parameter via an attribute value template; braces are required for evaluation.

Further examples:
Further examples, including function regex-group(), appear in the explanations of xsl:matching-substring and xsl:non-matching-substring.

Element definition:

XSLT 1.0:

Element unavailable in XSLT 1.0.

XSLT 2.0:

<!-- Category: instruction -->
<xsl:analyze-string
     select = expression
     regex = { string }
     flags? = { string } >

  <!-- Content: (xsl:matching-substring?, xsl:non-matching-substring?, xsl:fallback*) -->
</xsl:analyze-string>

  

back to top