matches
Whether a string matches a regular expression
Description
The fn:matches function determines whether a string matches a regular expression. The regular expression syntax used is defined by XML Schema with a few modifications/additions in XQueryXPath/XSLT 2.0. The $pattern argument is a regular expression. Unlike many of the string-related functions, the fn:matches function does not use collations at all. Regular expression matching is solely based on Unicode code points. Unless the anchors "^" or "$" are used, the function returns true if any substring of $input matches the regular expression.
Parameters |
Description |
|---|---|
input:string() |
the string to test |
pattern:string() |
the regular expression to test for |
flags:string() |
flags that control multiline mode, case insensitivity, etc. |
Examples
The examples below use this input document:
<xsl:variable name="address" as="xs:string">123 Main Street
Traverse City, MI 49684</xsl:variable>
XPath |
Results |
Explanation |
|---|---|---|
matches('query', 'q') |
true |
q appears in the string. |
matches('query', 'ue') |
true |
ue appears in the string. |
matches('query', '^qu') |
true |
^ anchors the pattern at the start. |
matches('query', 'qu$') |
false |
$ anchors the pattern at the end, and the string ends with ry. |
matches('query', '[ux]') |
true |
The string contains u. |
matches('query', 'q.*') |
true |
q followed by any characters. |
matches('query', '[a-z]{5}') |
true |
Five lowercase letters in a row. |
matches((), 'q' ) |
false |
The empty sequence is treated as a zero-length string, which does not contain q. |
matches('query', '[qu') |
Error FORX0002 |
[qu is not a valid regular expression: the bracket is not closed. |
matches($address, 'Street.*City') |
false |
Without the s flag, . does not match the line break. |
matches($address, 'Street.*City', 's') |
true |
With the s flag (dot-all), . also matches the line break. |
matches($address, 'Street$') |
false |
Without the m flag, $ only matches at the end of the whole string. |
matches($address, 'Street$', 'm') |
true |
With the m flag (multi-line), $ also matches at the end of each line. |
matches($address, 'street') |
false |
The match is case-sensitive. |
matches($address, 'street', 'i') |
true |
The i flag ignores case. |
matches($address, 'Main Street') |
true |
The text contains Main Street. |
matches($address, 'Main Street', 'x') |
false |
With the x flag, whitespace in the pattern is ignored, so it looks for MainStreet. |
matches($address, 'Main \s Street', 'x') |
true |
With the x flag, \s is needed to match the space. |
matches($address, 'street$', 'im') |
true |
i ignores case, and m lets $ match at the end of the first line. |
matches($address, 'Street$', 'q') |
false |
Since XPath 3.0 the q flag is valid: the pattern is taken as a literal string, so $ is not the end of a line. In XPath 2.0 it raised error FORX0001. |