XML technologies / Regular expressions / Features and dialects / Common metacharacters / Character classes and related constructs
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Modern regex dialects offer many ways to allow a selection of characters at a particular position, but every dialect has character classes.
Ordinary classes: [a-z] and [^a-z]
We have covered the basics, but remember that metacharacters inside and outside classes are quite different. For example, ˹*˼ is never special inside a class, while ˹-˼ usually is. Metacharacters such as ˹\b˼ can mean entirely different things inside and outside classes(see the table Some tools and their metacharacter shortcuts).
In most systems, class order and whether a range is written explicitly or as an interval do not affect efficiency: [0-9] behaves exactly like [9081726354]. Some implementations, notably Sun’s Java regex package, optimize ranges better, so ranges can have an advantage there.
A character class is always a positive assertion, or assertion: it must match one character. Even a negated class must match a character, simply one not listed. Think of it as a class matching all unlisted characters. Also heed the warning in the next section on dot and negated classes. Once, ˹[^LMNOP]˼ could safely be considered the same as ˹[\x00-KQ-\xFF]˼. That remains true in a purely 8-bit environment, but in Unicode systems with character values above 255 (\xFF), a negated class such as ˹[^LMNOP]˼ suddenly includes thousands of possible characters: all except L, M, N, O and P.
With ranges, know the character set and its structure. For example, ˹[a-Z]˼ is almost certainly a mistake, and certainly does not cover all letters. People often use ˹[a-zA-Z]˼ instead, at least in ASCII. Also consider the Unicode property \p{L}, discussed below in Unicode properties, scripts, and blocks: \p{Prop}, \P{Prop}. For binary data, however, a range such as \x80-\xFF can make perfect sense.
Almost any character: Dot
In some tools, dot abbreviates a class matching every possible character; in others, every character except newline. This matters in tools applying regexes to variables, or editor buffers, containing several logical lines. Also note:
In some Unicode-aware systems, such as Sun’s Java regex package, dot matches none of the Unicode line-ending characters(see Line endings in Unicode).
Some regex modes change dot’s meaning.
The POSIX standard says dot must not match NUL, the zero-valued byte, but every well-known scripting language allows it.
Dot or negated character class?
When applying regexes to multiline text, remember that dot often excludes newline, whereas a negated class such as ˹[^"]˼ includes it. Replacing ˹".*"˼ with ˹"[^"]*"˼ during development can therefore produce surprises. Dot-matches-all mode often changes this behavior(see Dot-matches-all mode).
Exactly one byte
Perl and PCRE, and therefore PHP, support \C, which matches one byte , even one that is part of a sequence encoding a character . All other constructs refer to characters. This can be dangerous: misuse may cause internal errors. Use it only if you know exactly what you are doing. I have found no use for it and will not discuss it further.
Unicode combining-character sequence: \X
Perl and PHP offer ˹\X˼, essentially an abbreviation for ˹\P{M}\p{M}*˼, something like an extended dot. ˹\X˼ matches a base character (base character, not a character from ˹\p{M}˼), followed by any number, including zero, of combining characters (combining characters, ˹\p{M}˼).
As explained earlier in Characters and character combinations, Unicode can combine a base and combining characters to look like one character, for example accented ě: e, U+0065 combined with breve ˘, U+0306, marking a short vowel. Multiple combining marks are possible: a Swiss German dictionary will need ö`, an o, U+006F, followed by diaeresis ¨, U+0308, and grave accent `, U+0300.
To match both francais and français, simply using ˹fran.ais˼ or ˹fran[cç]ais˼ is not enough: ç might be the single code point U+00C7 or c followed by cedilla, U+0063 and U+0327. For an exact match, perhaps use ˹fran(c¸?|ç)ais˼, but here ˹fran\Xais˼ is an excellent substitute for ˹fran.ais˼.
Besides matching the combining characters after a base character, ˹\X˼ differs from dot in other ways. First, ˹\X˼ always matches newline and other Unicode line endings; see Line endings in Unicode. Dot usually depends on dot-matches-all mode; see Dot-matches-all mode. Except for newline, dot always matches one character, but ˹\X˼ does not match a lone combining mark without a preceding base.
Character-class shortcuts: \w, \d, \s, \W, \D, \S
These shortcuts are widely supported:
\dDigit. The same as ˹
[0-9]˼;dstands for digit. In some Unicode-aware languages, this includes all Unicode digits.\DNon-digit. The same as ˹
[^0-9]˼.\wWord character. Often the same as ˹
[a-zA-Z0-9_]˼, but without underscore in some tools. Some include all characters considered alphanumeric in the chosen locale . With Unicode support, ˹\w˼ normally includes all alphanumerics, except injava.util.regexand PCRE, hence PHP, where ˹\w˼ is exactly the same as ˹[a-zA-Z0-9_]˼.\WNon-word character. The class containing every character except those matched by ˹
\w˼.\sWhitespace character. In ASCII-only systems, usually the same as ˹
[●\f\n\r\t\v]˼. Unicode systems usually add the control character next line, U+0085, and sometimes Unicode’s whitespace property, ˹\p{Z}˼; see the next section.\SNon-whitespace character. Generally the same as ˹
[^\s]˼.
As explained in the section on locales, POSIX locales can affect some shortcuts, especially ˹\w˼. With Unicode, ˹\w˼ often matches more characters, such as ˹\p{L}˼, discussed next, and underscore.
Unicode properties, scripts, and blocks: \p{Prop}, \P{Prop}
Superficially, Unicode just maps values to characters; see Unicode. But the standard goes further, assigning qualities to each character: lowercase letter, written right to left, mark intended for combination with a base, and so forth.
Regex support for these qualities varies greatly. Most Unicode-aware tools support at least some with ˹\p{qual}˼, matching characters with the quality, and ˹\P{qual}˼, matching characters without it. For example, ˹\p{L}˼. Here, ›L‹ denotes letter, as opposed to digit, punctuation, accent, and so on. ˹\p{L}˼ is an example of a general property, also called a category (category). We will encounter other qualities queryable with ˹\p{...}˼ and ˹\P{...}˼, but general properties are the most common.
The table lists Unicode’s general properties. Every character, or more precisely every code point, including those without a defined character, has exactly one. Their names are single letters: ›L‹ for Letter, ›S‹ for Symbol, and so on. Some systems, including Perl, also support clearer synonyms: ›Letter‹, ›Symbol‹, and so on.
Table: Basic Unicode properties.
Class | Synonym | Description |
|---|---|---|
|
| Letters |
|
| A mark: a character occurring only with a base character (base character), such as accents or enclosing boxes |
|
| Invisible separators, various kinds of space |
|
| Symbols, dingbats |
|
| Any kind of numeric character |
|
| Punctuation |
|
| Everything else, though rarely ordinary characters |
Some systems allow single-letter names without braces: ˹\pL˼ instead of ˹\p{L}˼. Some require or allow a prefix ›In‹ or ›Is‹, giving ˹\p{IsL}˼. Other qualities will provide examples where the Is/In prefix is mandatory. Note: as you will see in the table Unicode properties, scripts, and blocks in different languages, the story of Is and In is confusing. Earlier Unicode versions recommended one, now the other. I worked with the Perl 5.8.0 team to simplify this. Perl’s rule is now: “›Is‹ and ›In‹ are always optional, except for Unicode blocks, where ›In‹ is required as a prefix.”
Each single-letter Unicode property (property) is divided into two-letter subproperties; see the next table. Letter, for example, splits into lowercase, uppercase, titlecase, modifier, and other letters. Every letter code point belongs to exactly one of these.
Some implementations also have a composite subproperty, ˹\p{L&}˼, simply shorthand for ˹[\p{Lu}\p{Ll}\p{Lt}]˼.
The table also lists full synonyms, such as “Lowercase_Letter” for “Ll”, supported by some implementations. Unicode also permits similar spellings: ›LowercaseLetter‹, ›LOWERCASE_LETTER‹, ›Lowercase●Letter‹, ›lowercase-letter‹, and so on. I nevertheless recommend the table’s forms.
Table: Basic Unicode subproperties.
Property, synonym | Description | |
|---|---|---|
|
| Lowercase letters |
|
| Uppercase letters |
|
| Titlecase letters, used only at word starts. For example, Dž is the titlecase of uppercase DŽ or lowercase dž. |
| Shorthand for all characters in | |
|
| A few special letter-like characters |
|
| Letters that are neither lowercase, uppercase, nor accents, such as Hebrew, Arabic, Tibetan, and Japanese letters |
| ||
|
| Characters modifying others: accents, diacritics, vowel marks, stress marks |
|
| Modifying marks that occupy space themselves, mostly vowel signs in Bengali, Gujarati, Tamil, Telugu, Kannada, Malayalam, Sinhala, Myanmar, and Khmer |
|
| Enclosing marks, such as circles, squares, diamonds, and keycap symbols |
| ||
|
| Various spaces: ordinary and nonbreaking spaces, and spaces of different widths |
|
| The LINE SEPARATOR character ( |
|
| The PARAGRAPH SEPARATOR character ( |
| ||
|
| Mathematical symbols: |
|
| Currency symbols: |
|
| Mainly combining characters, here as standalone characters |
|
| Various dingbats, boxes, Braille characters, and Chinese nonletter characters |
| ||
|
| Zero to nine in various forms, excluding Chinese, Japanese, and Korean |
|
| Roman numerals |
|
| Superscript numbers and numeric symbols that are not digits, excluding Chinese, Japanese, and Korean |
| ||
|
| Hyphens, minus signs, and dashes of every kind |
|
| Opening delimiters such as |
|
| Closing delimiters such as |
|
| Opening quotation marks such as |
|
| Closing quotation marks such as |
|
| Special linguistic punctuation such as underscore |
|
| All remaining punctuation: |
| ||
|
| ASCII and Latin-1 control characters ( |
|
| Invisible formatting characters (Zero width joiner, Activate Arabic form shaping ...) |
|
| Private-use code points, for company logos and so on |
|
| Unused code points |
Scripts
Some systems allow matching a script using ˹\p{...}˼. For example, ˹\p{Hebrew}˼ matches characters explicitly belonging to Hebrew, not general characters shared with other scripts, such as spaces and punctuation.
Some scripts correspond to one language (Gujarati, Thai, Cherokee, and so on), others to several (Latin, Cyrillic). Languages such as Japanese use several scripts: Hiragana, Katakana, Han, Chinese characters, and Latin. Consult the tool’s documentation for details.
A Unicode script contains not every character used in a writing system, but those used exclusively or predominantly there. General characters such as spaces and punctuation are shared by almost all scripts and placed in the pseudoscript IsCommon . Another pseudoscript, Inherited, contains combining marks inheriting the script of their preceding base.
Blocks
Related to scripts but less versatile are Unicode blocks, ranges of code points. Tibetan contains the 256 characters from U+0F00 through U+0FFF. Characters in this block can be matched with \p{InTibetan} in Perl and \p{IsTibetan} in .NET languages. More on this later.
There are many blocks, at least one for each script (Hebrew, Tamil, Basic_Latin, Hangul_Jamo, Cyrillic, Katakana, ...) and character type (Currency, Arrows, Box_Drawing, Dingbats, ...).
Tibetan is a better block example: all its characters are genuinely Tibetan, and no specifically Tibetan characters lie outside it. Nevertheless, scripts are better than blocks:
Blocks can include unassigned code points. About 25% of the 256 characters in
Tibetanare undefined.Not every character expected in a block is actually there. For example,
Currencycontains neither the general currency sign ›¤‹ nor the rather important characters$, ¢, £, €and¥. (Fortunately the corresponding Unicode property is available instead,\p{Sc}.)Blocks often include characters that do not really belong. For example, the yen sign
¥appears inLatin_1_Supplement.What should belong to one script is often spread over several blocks. Greek letters, for example, occupy
GreekandGreek_Extended.
Nevertheless, blocks are supported more often than scripts. Confusion is inevitable: Unicode has both a block and a script called Tibetan.
Even naming is inconsistent. The table shows Tibetan’s block is called ˹\p{InTibetan}˼ in Perl and Java, but ˹\p{IsTibetan}˼ in .NET. The latter is a valid name in Perl for the Tibetan script.
Table: Unicode properties, scripts, and blocks in different languages.
Property | Perl | Java | .NET | PHP/PCRE | |
|---|---|---|---|---|---|
✓ | Basic properties such as | ✓ | ✓ | ✓ | ✓ |
✓ | Short forms such as | ✓ | ✓ | ✓ | |
Spelled-out properties such as | ✓ | ✓ | |||
✓ | Full names such as | ✓ | |||
✓ | Composite | ✓ | ✓ | ||
✓ | Scripts with | ✓ | ✓ | ||
Scripts with | ✓ | ||||
✓ | Blocks with | when no script exists | ✓ | ||
✓ | Blocks with | ✓ | ✓ | ||
Blocks with | ✓ | ||||
✓ | Negation with | ✓ | ✓ | ✓ | ✓ |
Negation with \p{^...} | ✓ | ✓ | |||
✓ |
| ✓ |
| ✓ | |
✓ |
| ✓ |
|
|
|
✓ |
| ✓ |
|
|
|
| |||||
A check mark in the left column recommends the feature for new implementations |
| ||||
For program versions, see: Program versions used in this book. | |||||
Other properties and qualities
Not every Unicode-aware language supports everything discussed above. The table provides an overview.
Unicode defines many more qualities accessible through ˹\p{...}˼, such as writing direction, left to right or right to left, and vowel signs. Some implementations allow user-defined properties. Consult the language’s documentation for further details.
Simple character-class subtraction: [[a-z]-[aeiou]]
.NET offers a simple way to subtract one class’s elements from another. For example, ˹[[a-z]-[aeiou]]˼ matches characters in ˹[a-z]˼ but not ˹[aeiou]˼: all lowercase ASCII letters except vowels.
Or ˹[\p{P}-[\p{Ps}\p{Pe}]]˼ is a class containing all characters in \p{P} except those in ˹[\p{Ps}\p{Pe}]˼: all punctuation except opening and closing delimiters.
Character-class set operations: [[a-z]&&[^aeiou]]
Sun’s Java regex package offers union, difference, and intersection on classes. An English-consonant class, for example, can be formed by subtracting “[a-z] minus [aeiou]”. Its notation differs from the previous section, especially subtraction, which looks odd initially. (Java writes the consonant example as [[a-z]&&[^aeiou]]). Before subtraction, consider the basic OR and AND operations.
OR adds characters by nesting a subclass inside an existing class instead of listing individual characters or ranges. [abcxyz] can also be written [[abc][xyz]], [abc[xyz]] or [[abc]xyz], and so on. OR combines sets into their union, much like the bitwise OR operator written ›|‹ or ›or‹ in many languages. Within a class, OR mainly offers convenience, but with negated classes it can be very useful in some situations.
AND resembles bitwise AND: only characters in both sets remain. The two classes are joined by &&. [\p{InThai}&&\P{Cn}], for example, matches all defined code points in the Thai block, by taking the intersection of \p{InThai} and \P{Cn}. Remember that \P{...}, with uppercase P, matches every character not having the specified quality, so \P{Cn} matches undefined code points. If Sun supported the Assigned quality, I would have used \p{Assigned} instead of \P{Cn}.
Do not confuse OR and AND. Whether these names are appropriate depends on perspective. Reading [[klipp][klar]] as “matches every character in [klipp] or in [klar] ” makes the name correct. Reading it as “the class contains characters from [klipp] and from [klar]” is equally correct, but contradicts the name.
AND is less ambiguous, since [\p{InThai}&&\P{Cn}] is normally read as “matches every character matched by \p{InThai} and also \P{Cn} ”, or sometimes “the allowed list is the intersection of \p{InThai} and \P{Cn}.”
These perspectives complicate communication: where I say OR and AND, others say union and intersection.
Character-class subtraction
Remember that \P{Cn} can also be written [^\p{Cn}], making the entire class the more complicated-looking [[\p{InThai}&&[^\p{Cn}]].
In words, “defined characters in the Thai block” means “characters in the Thai block minus undefined characters.” Double negation is confusing, but it should be clear that [\p{InThai}&&[^\p{Cn}]] means the same as “\p{InThai} minus \p{Cn}.”
This returns us to the consonant example in the heading: ˹[[a-z]&&[^aeiou]]˼. We now see how to subtract classes. The basic template is ˹[dies&&[^das]]˼, meaning “[dies] minus [das]”. Double negatives make my head spin; the structure ˹[... &&[^...]]˼ is easier to remember.
Emulating class set operations with lookaround
When lookaround is available but class set operations are not, see Lookahead; lookbehind, it can emulate them. The expression ˹[\p{InThai}&&[^\p{Cn}]]˼ can be replaced by the lookahead ˹(?!\p{Cn})\p{InThai}˼. Note: in Perl, simply using ˹\p{Thai}˼ works, since Perl considers \p{Thai} a script, which contains no undefined points. Other script/block differences are subtle and require documentation. Here the script actually lacks some block characters; see the character tables of the Unicode Consortium. This is probably less efficient than a real class, but almost as flexible. Lookahead permits four rewritings of this example; .NET needs IsThai instead of InThai; see Blocks:
(?!\p{Cn})\p{InThai}
(?=\P{Cn})\p{InThai}
\p{InThai}(?<!\p{Cn})
\p{InThai}(?<=\P{Cn})POSIX bracket expression: Character class [[:alpha:]]
POSIX calls what we call a character class a bracket expression. Note: bracket expression in English. Here I generally use character class and POSIX bracket expression synonymously for the whole construct, but POSIX character class means the specific ranges discussed here. POSIX uses character class for a feature inside a bracket expression.
In POSIX terminology, a character class is a special metasequence used in bracket expressions. For example, [:lower:] matches lowercase letters in the chosen locale; see Section on locales. In an English locale, or without one, it resembles a-z. It is allowed only inside a bracket expression, so ˹[[:lower:]]˼ is the class comparable to ˹[a-z]˼. Ugly, but it includes characters such as ö, ñ and so on, when the locale treats them as lowercase.
The full POSIX class list depends on the locale, but the following are usually supported.
Table: POSIX character classes.
Class | Description |
|---|---|
| Alphabetic and numeric characters |
| Alphabetic characters |
| Space and tab |
| Control characters |
| Digits |
| Visible characters, not spaces, tabs, controls, and so on |
| Lowercase letters |
| Like |
| Punctuation |
| Whitespace ( |
| Uppercase letters |
| Hexadecimal digits |
Some Unicode-aware languages extend POSIX bracket expressions to include Unicode properties; see Unicode properties, scripts, and blocks: \p{Prop}, \P{Prop}. Unicode constructs are more versatile and powerful and should be preferred when available.
POSIX bracket expression: Collating sequence [[.span-ll.]]
A locale can define collating sequences governing how characters or combinations are sorted and treated in similar operations. In Spanish, ll , as in tortilla, traditionally acts as one character, sorted between l and m . In German, ß lies between s and t but sorts as the two characters ss . Collating sequences define such rules, with names such as span-ll or eszet .
A sequence corresponding to several printed characters, such as span-ll, is one character to a POSIX system. A class such as ˹[^abc]˼ therefore matches the ›ll‹ combination.
Inside a bracket expression, a collating sequence uses [.....], so ˹torti[[.span-ll.]]a˼ matches tortilla. A collating sequence can match a character formed of several characters, so a single bracket expression may match multiple physical characters.
POSIX bracket expression: Equivalence class [[=n=]]
Some locales define equivalence classes , declaring characters equal for alphabetic sorting. A locale might define the class ›n‹ containing n and ñ, or a class ›a ‹ consisting of a, ä, á and à. Using notation similar to [:...:] but with ›=‹ instead of colon, equivalence classes can be used within POSIX bracket expressions: ˹[[=n=][=a=]]˼ matches all those accented characters (and naturally a and n).
An undefined equivalence class with a one-letter name falls back to that character in the chosen collating sequence. Every locale has ordinary letters as collating sequences, [.a.], [.b.], [.c.] and so on, so ˹[[=n=][=a=]]˼ becomes simply ˹[na]˼ when no equivalence classes are defined.
Emacs syntax classes
GNU Emacs does not support the usual ˹\w˼, ˹\s˼ and similar constructs. Instead, ˹\s˼ forms syntax classes:
\sZeichenMatches characters in Emacs syntax class character.
\SZeichenMatches characters not in that class.
˹\sw˼ matches a word character, and ˹\s-˼ a whitespace character. Most other systems use ˹\w˼ and ˹\s˼.
These syntax classes can be modified to specify which characters count as word characters. Emacs can thus adapt to the programming language of the file being edited.
German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln