XML technologies / XML Schema / Regexes for specifying simple datatypes / More atoms
(Excerpt from "XML Schema" by Eric van der Vlist)
You already know the simplest pattern atoms: “1”, “5”, and “\.” each match exactly one character. Other available atoms include special characters, a wildcard matching any character, and predefined or custom character classes.
Special characters
The table lists atoms matching one character, like those already seen, but representing characters requiring an escape or, for the first three, provided simply for convenience.
Table: special characters
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Wildcard
The character “.” has special meaning: it is a wildcard atom matching any valid XML character except newline and carriage return. Like any atom, “.” may have a quantifier. “.*” commonly specifies zero or more arbitrary characters. The following pattern matching integer multiples of 10 illustrates “.*” and the fact that xs:pattern is a Swiss Army knife:
<xs:simpleType name="multipleOfTen">
<xs:restriction base="xs:integer">
<xs:pattern value=".*0"/>
</xs:restriction>
</xs:simpleType>Character classes
W3C XML Schema adopted the classical Perl character classes and Unicode classes, but not POSIX-style classes, also available in Perl.
Classical Perl character classes
W3C XML Schema supports classical Perl classes with extensions for XML’s particular requirements. Each class is denoted by one letter. Classes identified by uppercase and lowercase forms of the same letter are complementary:
\s | Whitespace. Matches XML whitespace: space #x20, tab #x09, newline #x0A, and carriage return #x0D. |
\S | Non-whitespace characters. |
\d | Digits, 0 to 9 and digits from other alphabets. |
\D | Nondigit characters. |
\w | Extended word characters: any Unicode character not defined as punctuation, separator, or other. This agrees with Perl’s definition when UTF8 support is enabled. |
\W | Nonword characters. |
\i | XML 1.0 name-start characters: all letters and “_”. This extends W3C XML Schema beyond Perl’s regular expressions. |
\I | Characters not permitted at the start of an XML name. |
\c | XML 1.0 name characters: name-start characters, digits, “.”, “:”, “-”, and characters Unicode defines as Combining or Extender. This extends W3C XML Schema beyond Perl’s regular expressions. |
\C | Characters not permitted in an XML 1.0 name. |
Like other atoms, these classes may have a quantifier. Our previous pattern:
<xs:pattern value=".*0"/>
restricts the lexical space to strings ending in zero. If the base type is xs:integer , that is adequate; but for xs:decimal or xs:string, we could restrict it further by writing:
<xs:pattern value="-?\d*0"/>
This ensures the characters before the final zero are digits, optionally preceded by -. Later, in “Fixed format”, we will see how to specify an optional leading - or +.
Unicode character classes
Patterns support classes matching Unicode categories and blocks. Categories and blocks are complementary classifications: categories classify characters by use regardless of geographic origin—letters, uppercase letters, digits, punctuation, and so on—whereas blocks classify by origin regardless of use: Latin, Arabic, Hebrew, Tibetan, even Gothic or musical notation.
The notation \p{Name} is similar for blocks and categories. The prefix Is is added to category names to distinguish them. The notation \P{Name} also selects characters outside the specified block or category. The specification lists Unicode blocks and categories. The next table shows Unicode character classes, followed by Unicode blocks.
Table: Unicode character classes
Unicode character class | Contains |
|---|---|
C | Other characters: nonletters, nonsymbols, nonnumbers, nonseparators |
Cc | Control characters |
Cf | Format characters |
Cn | Unassigned code points |
Co | Private-use characters |
L | Letters |
No | Other numbers |
P | Punctuation |
Pc | Connector punctuation |
Pd | Dashes |
Pe | Closing punctuation |
Pf | Final quotation marks, possibly behaving like Ps or Pe |
Mc | Spacing combining marks |
Me | Enclosing marks |
Mn | Nonspacing marks |
N | Numbers |
Nd | Decimal digits |
Nl | Letter numbers |
Ll | Lowercase letters |
Lm | Modifier letters |
Lo | Other letters |
Lt | Titlecase letters |
Lu | Uppercase letters |
M | All marks |
Pi | Initial quotation marks, possibly behaving like Ps or Pe |
Po | Other punctuation |
Ps | Opening punctuation |
S | Symbols |
Sc | Currency symbols |
Sk | Modifier symbols |
Sm | Mathematical symbols |
So | Other symbols |
Z | Separators |
Zl | Line separators |
Zp | Paragraph separators |
Zs | Whitespace |
Table: Unicode character blocks
AlphabeticPresentationForms | Arabic | ArabicPresentationForms-A |
ArabicPresentationForms-B | Armenian | Arrows |
BasicLatin | Bengali | BlockElements |
Bopomofo | BopomofoExtended | BoxDrawing |
BraillePatterns | ByzantineMusicalSymbols | Cherokee |
CJKCompatibility | CJKCompatibilityForms | CJKCompatibilityIdeographs |
CJKCompatibilityIdeographsSupplement | CJKRadicalsSupplement | CJKSymbolsandPunctuation |
CJKUnifiedIdeographs | CJKUnifiedIdeographsExtensionA | CJKUnifiedIdeographsExtensionB |
CombiningDiacriticalMarks | CombiningHalfMarks | CombiningMarksforSymbols |
ControlPictures | CurrencySymbols | Cyrillic |
Deseret | Devanagari | Dingbats |
EnclosedAlphanumerics | EnclosedCJKLettersandMonths | Ethiopic |
GeneralPunctuation | GeometricShapes | Georgian |
Gothic | Greek | GreekExtended |
Gujarati | Gurmukhi | HalfwidthandFullwidthForms |
HangulCompatibilityJamo | HangulJamo | HangulSyllables |
Hebrew | HighPrivateUseSurrogates | HighSurrogates |
Hiragana | IdeographicDescriptionCharacters | IPAExtensions |
Kanbun | KangxiRadicals | Kannada |
Katakana | Khmer | Lao |
Latin-1Supplement | LatinExtended-A | LatinExtendedAdditional |
LatinExtended-B | LetterlikeSymbols | LowSurrogates |
Malayalam | MathematicalAlphanumericSymbols | MathematicalOperators |
MiscellaneousSymbols | MiscellaneousTechnical | Mongolian |
MusicalSymbols | Myanmar | NumberForms |
Ogham | OldItalic | OpticalCharacterRecognition |
Oriya | PrivateUse | PrivateUse |
PrivateUse | Runic | Sinhala |
SmallFormVariants | SpacingModifierLetters | Specials |
Specials | SuperscriptsandSubscripts | Syriac |
Tags | Tamil | Telugu |
Thaana | Thai | Tibetan |
UnifiedCanadianAboriginalSyllabics | YiRadicals | YiSyllables |
We do not yet know how to express the intersection of a block and category in one pattern, or specify a datatype containing only basic Latin letters. To cross these classifications and define the intersection of block L, all letters, with the category BasicLatin, ASCII characters below #x7F, we can use two successive restrictions:
<xs:simpleType name="BasicLatinLetters">
<xs:restriction>
<xs:simpleType>
<xs:restriction base="xs:token">
<xs:pattern value="\p{IsBasicLatin}*"/>
</xs:restriction>
</xs:simpleType>
<xs:pattern value="\p{L}*"/>
</xs:restriction>
</xs:simpleType>Custom character classes
These are character lists in square brackets, accepting - for ranges and an initial ^ to negate the entire list:
[azertyuiop]
defines the letters on a French keyboard’s top row;
[a-z]
specifies every letter from “a” through “z”, inclusive;
[^a-z]
denotes letters outside “a” through “z”, but
[-^\\]
defines “-”, “^”, and “\”, while
[-+]
matches a number’s sign.
These examples show that square brackets have their own syntax and semantics. As with regex notation generally, there is a list of atoms. Rather than matching each atom against an instance-string character, however, we define a logical space. The class represents the set of characters matching any atom between the brackets.
Two special characters also have position-dependent meanings. The character - denotes a range when between, for example, a and z, but is ordinary immediately after the opening or before the closing bracket: [+-] and [-+] are both valid. Conversely, ^ negates a class when first, but becomes ordinary elsewhere in the definition.
Backslash is the escape character: “\\” is used to mean “\”. In a class, all escape sequences already seen as atoms may be used. Even characters losing their special meaning inside brackets may still be escaped. Thus, the class
[-^\\]
can also be written
[\-\^\\]
or
[\^\\-]
, since escaped characters’ order no longer matters.
Inside brackets, “\” still introduces Perl or Unicode class references. The expression
[\d\p{Lu}]
denotes decimal digits, Perl class \d , and uppercase letters, Unicode category Lu.
Mathematicians have shown that three basic operations suffice for sets, chosen from a larger range of operations. We have already seen two within brackets: union, an implicit union of the atoms, and complement, where an initial ^ complements the set defined by the rest of the brackets. W3C XML Schema extends Perl’s regex rules with a third operation: set difference. The notation
[menge1-[menge2]]
denotes every character in menge1 that is not in menge2. Both menge1 and menge2 may use every syntax trick seen so far.
This operator can form class intersections: A intersect B is A minus B’s complement. We can now define a class BasicLatinLetters :
[\p{IsBasicLatin}-[^\p{L}]]
Or write the class using \P, also denoting complement:
[\p{IsBasicLatin}-[\P{L}]]
The corresponding datatype definition would be:
<xs:simpleType name="BasicLatinLetters">
<xs:restriction base="xs:token">
<xs:pattern value="[\p{IsBasicLatin}-[\P{L}]]*"/>
</xs:restriction>
</xs:simpleType>Alternation and grouping
Our first example used three separate patterns for three possible values. The character “|”, acting as OR outside brackets, makes the definition more compact. The simple type then becomes:
<xs:simpleType name="myByte">
<xs:restriction base="xs:byte">
<xs:pattern value="1|5|15"/>
</xs:restriction>
</xs:simpleType>This is more concise, though not necessarily clearer. Alternation becomes interesting with groups: complete regexes treated as atoms, optionally quantified to build fuller, more complex expressions. Groups use parentheses “(” and “)”. A comma-separated list of “1”, “5”, or “15”, ignoring whitespace between values and commas, could use this pattern:
<xs:simpleType name="myListOfBytes">
<xs:restriction base="xs:token">
<xs:pattern value="(1|5|15)( *, *(1|5|15))*"/>
</xs:restriction>
</xs:simpleType>Here, we rely on the base datatype’s whitespace processing: xs:token collapses whitespace. We did not check leading or trailing whitespace because it is removed anyway, and checked only single spaces around commas with this atom:
runback " * " runback
Copyright © 2003 O'Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "XML Schema" has the same terms as the printed edition. The work and all its parts are copyright-protected. All rights reserved, including reproduction, translation, microfilming, and storage or processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de