XML technologies / XML Schema / Regular expressions for specifying simple datatypes / The simplest possible patterns

(Excerpt from "XML Schema" by Eric van der Vlist)

In their simplest form, patterns act as enumerations applied to lexical space rather than value space.

For a byte limited to “1”, “5” or “15”, the classic datatype definition uses facet xs:enumeration:

<xs:simpleType name="myByte">
  <xs:restriction base="xs:byte">
    <xs:enumeration value="1"/>
    <xs:enumeration value="5"/>
    <xs:enumeration value="15"/>
  </xs:restriction>
</xs:simpleType>

This is the normal definition for a type belonging to the lexical and value spaces of xs:byte paßt. It accepts values such as “1”, “5” and “15”, but also “01” or “0000005”. However, one characteristic of xs:pattern is that no additional facet may restrict lexical space. If leading zeros are a problem, patterns can define the type instead of enumerations:

<xs:simpleType name="myByte">
  <xs:restriction base="xs:byte">
    <xs:pattern value="1"/>
    <xs:pattern value="5"/>
    <xs:pattern value="15"/>
  </xs:restriction>
</xs:simpleType>

The new datatype still derives from xs:byte and retains byte semantics, but its lexical space now accepts only “1”, “5” and “15”, excluding equivalent values with other lexical representations.

This differs importantly from Perl regexes, on which W3C XML Schema patterns are based. Perl’s /15/ matches any string containing “15”, whereas in W3C XML Schema the pattern matches only the exact string “15”. The equivalent Perl expression is /^15$/ .

This example deliberately avoids pattern metacharacters: “.” “\” “?” “*” “+” “{” “}” “(” “)” “[” “]”. Their meanings are explained later. For now, prefix any of them with “\” to interpret it literally. For a similar decimal type whose lexical space is restricted to “1” and “1.5”, write:

<xs:simpleType name="myDecimal">
  <xs:restriction base="xs:decimal">
    <xs:pattern value="1"/>
    <xs:pattern value="1\.5"/>
  </xs:restriction>
</xs:simpleType>

A common source of errors is failing to prefix ordinary characters with an escape. As we will see, a preceding “\” changes their meaning. For example, “\P” matches all Unicode punctuation characters, not the letter “P”.

   

 

 

 

back to top