How to Use Regex in XML Schema (XSD)
This article provides a comprehensive guide on validating XML document data using custom regular expressions within an XML Schema Definition (XSD). You will learn the core schema elements required for pattern matching, the specific behavior of XSD regular expression syntax, and how to implement single and multiple pattern constraints through practical examples.
The <xs:pattern>
Facet
In XML Schema, custom regular expressions are applied using the
<xs:pattern> facet. This facet restricts the
allowable lexical values of a simple type (or simple content) to strings
that match a specified regular expression.
To apply a regular expression: 1. Define a
<xs:simpleType>. 2. Add an
<xs:restriction> targeting a base data type (commonly
xs:string or xs:token). 3. Insert an
<xs:pattern> element inside the restriction and set
its value attribute to your regular expression.
Basic Implementation Example
The following example defines an element named
PostalCode that only accepts standard 5-digit US ZIP codes
or 5-digit ZIP codes with a 4-digit extension:
<xs:element name="PostalCode">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="\d{5}(-\d{4})?"/>
</xs:restriction>
</xs:simpleType>
</xs:element>Key Characteristics of XSD Regular Expressions
XSD regular expressions are defined by the W3C XML Schema specification and have specific behaviors that differ from typical programming languages like JavaScript, Python, or Perl:
- Implicit Exact Matching: The regular expression
automatically matches the entire content of the element from start to
finish. Anchors like
^(start of string) and$(end of string) are not supported and will result in a schema validation error if used. - Character Classes: Standard shorthand classes are
supported, such as
\d(digits),\D(non-digits),\s(whitespace),\S(non-whitespace),\w(word characters), and\W(non-word characters). - Unicode Support: You can use Unicode character
properties with
\p{...}(matches characters in a property) and\P{...}(matches characters not in a property), such as\p{Lu}for uppercase letters. - Character Class Subtraction: XSD allows subtracting
characters from a class using the
-[...]syntax (for example,[a-z-[aeiou]]matches any lowercase consonant).
Applying Multiple Patterns (Logical OR)
When you specify multiple <xs:pattern> elements
inside the same <xs:restriction>, the XML validator
evaluates them using a logical OR operation. An element’s
value is considered valid if it satisfies at least one of the defined
patterns.
<xs:simpleType name="ProductCodeType">
<xs:restriction base="xs:string">
<!-- Format A: Two letters followed by three digits (e.g., AB123) -->
<xs:pattern value="[A-Z]{2}\d{3}"/>
<!-- Format B: Four digits followed by a hyphen and a letter (e.g., 1234-X) -->
<xs:pattern value="\d{4}-[A-Z]"/>
</xs:restriction>
</xs:simpleType>In this case, any XML value matching either format will pass schema validation.