1PERLRECHARCLASS(1)     Perl Programmers Reference Guide     PERLRECHARCLASS(1)
2
3
4

NAME

6       perlrecharclass - Perl Regular Expression Character Classes
7

DESCRIPTION

9       The top level documentation about Perl regular expressions is found in
10       perlre.
11
12       This manual page discusses the syntax and use of character classes in
13       Perl Regular Expressions.
14
15       A character class is a way of denoting a set of characters, in such a
16       way that one character of the set is matched.  It's important to
17       remember that matching a character class consumes exactly one character
18       in the source string. (The source string is the string the regular
19       expression is matched against.)
20
21       There are three types of character classes in Perl regular expressions:
22       the dot, backslashed sequences, and the bracketed form.
23
24   The dot
25       The dot (or period), "." is probably the most used, and certainly the
26       most well-known character class. By default, a dot matches any
27       character, except for the newline. The default can be changed to add
28       matching the newline with the single line modifier: either for the
29       entire regular expression using the "/s" modifier, or locally using
30       "(?s)".
31
32       Here are some examples:
33
34        "a"  =~  /./       # Match
35        "."  =~  /./       # Match
36        ""   =~  /./       # No match (dot has to match a character)
37        "\n" =~  /./       # No match (dot does not match a newline)
38        "\n" =~  /./s      # Match (global 'single line' modifier)
39        "\n" =~  /(?s:.)/  # Match (local 'single line' modifier)
40        "ab" =~  /^.$/     # No match (dot matches one character)
41
42   Backslashed sequences
43       Perl regular expressions contain many backslashed sequences that
44       constitute a character class. That is, they will match a single
45       character, if that character belongs to a specific set of characters
46       (defined by the sequence). A backslashed sequence is a sequence of
47       characters starting with a backslash. Not all backslashed sequences are
48       character class; for a full list, see perlrebackslash.
49
50       Here's a list of the backslashed sequences, which are discussed in more
51       detail below.
52
53        \d             Match a digit character.
54        \D             Match a non-digit character.
55        \w             Match a "word" character.
56        \W             Match a non-"word" character.
57        \s             Match a white space character.
58        \S             Match a non-white space character.
59        \h             Match a horizontal white space character.
60        \H             Match a character that isn't horizontal white space.
61        \v             Match a vertical white space character.
62        \V             Match a character that isn't vertical white space.
63        \pP, \p{Prop}  Match a character matching a Unicode property.
64        \PP, \P{Prop}  Match a character that doesn't match a Unicode property.
65
66       Digits
67
68       "\d" matches a single character that is considered to be a digit.  What
69       is considered a digit depends on the internal encoding of the source
70       string. If the source string is in UTF-8 format, "\d" not only matches
71       the digits '0' - '9', but also Arabic, Devanagari and digits from other
72       languages. Otherwise, if there is a locale in effect, it will match
73       whatever characters the locale considers digits. Without a locale, "\d"
74       matches the digits '0' to '9'.  See "Locale, Unicode and UTF-8".
75
76       Any character that isn't matched by "\d" will be matched by "\D".
77
78       Word characters
79
80       "\w" matches a single word character: an alphanumeric character (that
81       is, an alphabetic character, or a digit), or the underscore ("_").
82       What is considered a word character depends on the internal encoding of
83       the string. If it's in UTF-8 format, "\w" matches those characters that
84       are considered word characters in the Unicode database. That is, it not
85       only matches ASCII letters, but also Thai letters, Greek letters, etc.
86       If the source string isn't in UTF-8 format, "\w" matches those
87       characters that are considered word characters by the current locale.
88       Without a locale in effect, "\w" matches the ASCII letters, digits and
89       the underscore.
90
91       Any character that isn't matched by "\w" will be matched by "\W".
92
93       White space
94
95       "\s" matches any single character that is consider white space. In the
96       ASCII range, "\s" matches the horizontal tab ("\t"), the new line
97       ("\n"), the form feed ("\f"), the carriage return ("\r"), and the space
98       (the vertical tab, "\cK" is not matched by "\s").  The exact set of
99       characters matched by "\s" depends on whether the source string is in
100       UTF-8 format. If it is, "\s" matches what is considered white space in
101       the Unicode database. Otherwise, if there is a locale in effect, "\s"
102       matches whatever is considered white space by the current locale.
103       Without a locale, "\s" matches the five characters mentioned in the
104       beginning of this paragraph.  Perhaps the most notable difference is
105       that "\s" matches a non-breaking space only if the non-breaking space
106       is in a UTF-8 encoded string.
107
108       Any character that isn't matched by "\s" will be matched by "\S".
109
110       "\h" will match any character that is considered horizontal white
111       space; this includes the space and the tab characters. "\H" will match
112       any character that is not considered horizontal white space.
113
114       "\v" will match any character that is considered vertical white space;
115       this includes the carriage return and line feed characters (newline).
116       "\V" will match any character that is not considered vertical white
117       space.
118
119       "\R" matches anything that can be considered a newline under Unicode
120       rules. It's not a character class, as it can match a multi-character
121       sequence. Therefore, it cannot be used inside a bracketed character
122       class. Details are discussed in perlrebackslash.
123
124       "\h", "\H", "\v", "\V", and "\R" are new in perl 5.10.0.
125
126       Note that unlike "\s", "\d" and "\w", "\h" and "\v" always match the
127       same characters, regardless whether the source string is in UTF-8
128       format or not. The set of characters they match is also not influenced
129       by locale.
130
131       One might think that "\s" is equivalent with "[\h\v]". This is not
132       true.  The vertical tab ("\x0b") is not matched by "\s", it is however
133       considered vertical white space. Furthermore, if the source string is
134       not in UTF-8 format, the next line ("\x85") and the no-break space
135       ("\xA0") are not matched by "\s", but are by "\v" and "\h"
136       respectively.  If the source string is in UTF-8 format, both the next
137       line and the no-break space are matched by "\s".
138
139       The following table is a complete listing of characters matched by
140       "\s", "\h" and "\v".
141
142       The first column gives the code point of the character (in hex format),
143       the second column gives the (Unicode) name. The third column indicates
144       by which class(es) the character is matched.
145
146        0x00009        CHARACTER TABULATION   h s
147        0x0000a              LINE FEED (LF)    vs
148        0x0000b             LINE TABULATION    v
149        0x0000c              FORM FEED (FF)    vs
150        0x0000d        CARRIAGE RETURN (CR)    vs
151        0x00020                       SPACE   h s
152        0x00085             NEXT LINE (NEL)    vs  [1]
153        0x000a0              NO-BREAK SPACE   h s  [1]
154        0x01680            OGHAM SPACE MARK   h s
155        0x0180e   MONGOLIAN VOWEL SEPARATOR   h s
156        0x02000                     EN QUAD   h s
157        0x02001                     EM QUAD   h s
158        0x02002                    EN SPACE   h s
159        0x02003                    EM SPACE   h s
160        0x02004          THREE-PER-EM SPACE   h s
161        0x02005           FOUR-PER-EM SPACE   h s
162        0x02006            SIX-PER-EM SPACE   h s
163        0x02007                FIGURE SPACE   h s
164        0x02008           PUNCTUATION SPACE   h s
165        0x02009                  THIN SPACE   h s
166        0x0200a                  HAIR SPACE   h s
167        0x02028              LINE SEPARATOR    vs
168        0x02029         PARAGRAPH SEPARATOR    vs
169        0x0202f       NARROW NO-BREAK SPACE   h s
170        0x0205f   MEDIUM MATHEMATICAL SPACE   h s
171        0x03000           IDEOGRAPHIC SPACE   h s
172
173       [1] NEXT LINE and NO-BREAK SPACE only match "\s" if the source string
174           is in UTF-8 format.
175
176       It is worth noting that "\d", "\w", etc, match single characters, not
177       complete numbers or words. To match a number (that consists of
178       integers), use "\d+"; to match a word, use "\w+".
179
180       Unicode Properties
181
182       "\pP" and "\p{Prop}" are character classes to match characters that fit
183       given Unicode classes. One letter classes can be used in the "\pP"
184       form, with the class name following the "\p", otherwise, the property
185       name is enclosed in braces, and follows the "\p". For instance, a match
186       for a number can be written as "/\pN/" or as "/\p{Number}/".  Lowercase
187       letters are matched by the property LowercaseLetter which has as short
188       form Ll. They have to be written as "/\p{Ll}/" or
189       "/\p{LowercaseLetter}/". "/\pLl/" is valid, but means something
190       different.  It matches a two character string: a letter (Unicode
191       property "\pL"), followed by a lowercase "l".
192
193       For a list of possible properties, see "Unicode Character Properties"
194       in perlunicode. It is also possible to defined your own properties.
195       This is discussed in "User-Defined Character Properties" in
196       perlunicode.
197
198       Examples
199
200        "a"  =~  /\w/      # Match, "a" is a 'word' character.
201        "7"  =~  /\w/      # Match, "7" is a 'word' character as well.
202        "a"  =~  /\d/      # No match, "a" isn't a digit.
203        "7"  =~  /\d/      # Match, "7" is a digit.
204        " "  =~  /\s/      # Match, a space is white space.
205        "a"  =~  /\D/      # Match, "a" is a non-digit.
206        "7"  =~  /\D/      # No match, "7" is not a non-digit.
207        " "  =~  /\S/      # No match, a space is not non-white space.
208
209        " "  =~  /\h/      # Match, space is horizontal white space.
210        " "  =~  /\v/      # No match, space is not vertical white space.
211        "\r" =~  /\v/      # Match, a return is vertical white space.
212
213        "a"  =~  /\pL/     # Match, "a" is a letter.
214        "a"  =~  /\p{Lu}/  # No match, /\p{Lu}/ matches upper case letters.
215
216        "\x{0e0b}" =~ /\p{Thai}/  # Match, \x{0e0b} is the character
217                                  # 'THAI CHARACTER SO SO', and that's in
218                                  # Thai Unicode class.
219        "a"  =~  /\P{Lao}/ # Match, as "a" is not a Laoian character.
220
221   Bracketed Character Classes
222       The third form of character class you can use in Perl regular
223       expressions is the bracketed form. In its simplest form, it lists the
224       characters that may be matched inside square brackets, like this:
225       "[aeiou]".  This matches one of "a", "e", "i", "o" or "u". Just as the
226       other character classes, exactly one character will be matched. To
227       match a longer string consisting of characters mentioned in the
228       characters class, follow the character class with a quantifier. For
229       instance, "[aeiou]+" matches a string of one or more lowercase ASCII
230       vowels.
231
232       Repeating a character in a character class has no effect; it's
233       considered to be in the set only once.
234
235       Examples:
236
237        "e"  =~  /[aeiou]/        # Match, as "e" is listed in the class.
238        "p"  =~  /[aeiou]/        # No match, "p" is not listed in the class.
239        "ae" =~  /^[aeiou]$/      # No match, a character class only matches
240                                  # a single character.
241        "ae" =~  /^[aeiou]+$/     # Match, due to the quantifier.
242
243       Special Characters Inside a Bracketed Character Class
244
245       Most characters that are meta characters in regular expressions (that
246       is, characters that carry a special meaning like "*" or "(") lose their
247       special meaning and can be used inside a character class without the
248       need to escape them. For instance, "[()]" matches either an opening
249       parenthesis, or a closing parenthesis, and the parens inside the
250       character class don't group or capture.
251
252       Characters that may carry a special meaning inside a character class
253       are: "\", "^", "-", "[" and "]", and are discussed below. They can be
254       escaped with a backslash, although this is sometimes not needed, in
255       which case the backslash may be omitted.
256
257       The sequence "\b" is special inside a bracketed character class. While
258       outside the character class "\b" is an assertion indicating a point
259       that does not have either two word characters or two non-word
260       characters on either side, inside a bracketed character class, "\b"
261       matches a backspace character.
262
263       A "[" is not special inside a character class, unless it's the start of
264       a POSIX character class (see below). It normally does not need
265       escaping.
266
267       A "]" is either the end of a POSIX character class (see below), or it
268       signals the end of the bracketed character class. Normally it needs
269       escaping if you want to include a "]" in the set of characters.
270       However, if the "]" is the first (or the second if the first character
271       is a caret) character of a bracketed character class, it does not
272       denote the end of the class (as you cannot have an empty class) and is
273       considered part of the set of characters that can be matched without
274       escaping.
275
276       Examples:
277
278        "+"   =~ /[+?*]/     #  Match, "+" in a character class is not special.
279        "\cH" =~ /[\b]/      #  Match, \b inside in a character class
280                             #  is equivalent with a backspace.
281        "]"   =~ /[][]/      #  Match, as the character class contains.
282                             #  both [ and ].
283        "[]"  =~ /[[]]/      #  Match, the pattern contains a character class
284                             #  containing just ], and the character class is
285                             #  followed by a ].
286
287       Character Ranges
288
289       It is not uncommon to want to match a range of characters. Luckily,
290       instead of listing all the characters in the range, one may use the
291       hyphen ("-").  If inside a bracketed character class you have two
292       characters separated by a hyphen, it's treated as if all the characters
293       between the two are in the class. For instance, "[0-9]" matches any
294       ASCII digit, and "[a-m]" matches any lowercase letter from the first
295       half of the ASCII alphabet.
296
297       Note that the two characters on either side of the hyphen are not
298       necessary both letters or both digits. Any character is possible,
299       although not advisable.  "['-?]" contains a range of characters, but
300       most people will not know which characters that will be. Furthermore,
301       such ranges may lead to portability problems if the code has to run on
302       a platform that uses a different character set, such as EBCDIC.
303
304       If a hyphen in a character class cannot be part of a range, for
305       instance because it is the first or the last character of the character
306       class, or if it immediately follows a range, the hyphen isn't special,
307       and will be considered a character that may be matched. You have to
308       escape the hyphen with a backslash if you want to have a hyphen in your
309       set of characters to be matched, and its position in the class is such
310       that it can be considered part of a range.
311
312       Examples:
313
314        [a-z]       #  Matches a character that is a lower case ASCII letter.
315        [a-fz]      #  Matches any letter between 'a' and 'f' (inclusive) or the
316                    #  letter 'z'.
317        [-z]        #  Matches either a hyphen ('-') or the letter 'z'.
318        [a-f-m]     #  Matches any letter between 'a' and 'f' (inclusive), the
319                    #  hyphen ('-'), or the letter 'm'.
320        ['-?]       #  Matches any of the characters  '()*+,-./0123456789:;<=>?
321                    #  (But not on an EBCDIC platform).
322
323       Negation
324
325       It is also possible to instead list the characters you do not want to
326       match. You can do so by using a caret ("^") as the first character in
327       the character class. For instance, "[^a-z]" matches a character that is
328       not a lowercase ASCII letter.
329
330       This syntax make the caret a special character inside a bracketed
331       character class, but only if it is the first character of the class. So
332       if you want to have the caret as one of the characters you want to
333       match, you either have to escape the caret, or not list it first.
334
335       Examples:
336
337        "e"  =~  /[^aeiou]/   #  No match, the 'e' is listed.
338        "x"  =~  /[^aeiou]/   #  Match, as 'x' isn't a lowercase vowel.
339        "^"  =~  /[^^]/       #  No match, matches anything that isn't a caret.
340        "^"  =~  /[x^]/       #  Match, caret is not special here.
341
342       Backslash Sequences
343
344       You can put a backslash sequence character class inside a bracketed
345       character class, and it will act just as if you put all the characters
346       matched by the backslash sequence inside the character class. For
347       instance, "[a-f\d]" will match any digit, or any of the lowercase
348       letters between 'a' and 'f' inclusive.
349
350       Examples:
351
352        /[\p{Thai}\d]/     # Matches a character that is either a Thai
353                           # character, or a digit.
354        /[^\p{Arabic}()]/  # Matches a character that is neither an Arabic
355                           # character, nor a parenthesis.
356
357       Backslash sequence character classes cannot form one of the endpoints
358       of a range.
359
360       Posix Character Classes
361
362       Posix character classes have the form "[:class:]", where class is name,
363       and the "[:" and ":]" delimiters. Posix character classes appear inside
364       bracketed character classes, and are a convenient and descriptive way
365       of listing a group of characters. Be careful about the syntax,
366
367        # Correct:
368        $string =~ /[[:alpha:]]/
369
370        # Incorrect (will warn):
371        $string =~ /[:alpha:]/
372
373       The latter pattern would be a character class consisting of a colon,
374       and the letters "a", "l", "p" and "h".
375
376       Perl recognizes the following POSIX character classes:
377
378        alpha  Any alphabetical character.
379        alnum  Any alphanumerical character.
380        ascii  Any ASCII character.
381        blank  A GNU extension, equal to a space or a horizontal tab ("\t").
382        cntrl  Any control character.
383        digit  Any digit, equivalent to "\d".
384        graph  Any printable character, excluding a space.
385        lower  Any lowercase character.
386        print  Any printable character, including a space.
387        punct  Any punctuation character.
388        space  Any white space character. "\s" plus the vertical tab ("\cK").
389        upper  Any uppercase character.
390        word   Any "word" character, equivalent to "\w".
391        xdigit Any hexadecimal digit, '0' - '9', 'a' - 'f', 'A' - 'F'.
392
393       The exact set of characters matched depends on whether the source
394       string is internally in UTF-8 format or not. See "Locale, Unicode and
395       UTF-8".
396
397       Most POSIX character classes have "\p" counterparts. The difference is
398       that the "\p" classes will always match according to the Unicode
399       properties, regardless whether the string is in UTF-8 format or not.
400
401       The following table shows the relation between POSIX character classes
402       and the Unicode properties:
403
404        [[:...:]]   \p{...}      backslash
405
406        alpha       IsAlpha
407        alnum       IsAlnum
408        ascii       IsASCII
409        blank
410        cntrl       IsCntrl
411        digit       IsDigit      \d
412        graph       IsGraph
413        lower       IsLower
414        print       IsPrint
415        punct       IsPunct
416        space       IsSpace
417                    IsSpacePerl  \s
418        upper       IsUpper
419        word        IsWord
420        xdigit      IsXDigit
421
422       Some character classes may have a non-obvious name:
423
424       cntrl
425           Any control character. Usually, control characters don't produce
426           output as such, but instead control the terminal somehow: for
427           example newline and backspace are control characters. All
428           characters with "ord()" less than 32 are usually classified as
429           control characters (in ASCII, the ISO Latin character sets, and
430           Unicode), as is the character "ord()" value of 127 ("DEL").
431
432       graph
433           Any character that is graphical, that is, visible. This class
434           consists of all the alphanumerical characters and all punctuation
435           characters.
436
437       print
438           All printable characters, which is the set of all the graphical
439           characters plus the space.
440
441       punct
442           Any punctuation (special) character.
443
444       Negation
445
446       A Perl extension to the POSIX character class is the ability to negate
447       it. This is done by prefixing the class name with a caret ("^").  Some
448       examples:
449
450        POSIX         Unicode       Backslash
451        [[:^digit:]]  \P{IsDigit}   \D
452        [[:^space:]]  \P{IsSpace}   \S
453        [[:^word:]]   \P{IsWord}    \W
454
455       [= =] and [. .]
456
457       Perl will recognize the POSIX character classes "[=class=]", and
458       "[.class.]", but does not (yet?) support this construct. Use of such a
459       construct will lead to an error.
460
461       Examples
462
463        /[[:digit:]]/            # Matches a character that is a digit.
464        /[01[:lower:]]/          # Matches a character that is either a
465                                 # lowercase letter, or '0' or '1'.
466        /[[:digit:][:^xdigit:]]/ # Matches a character that can be anything,
467                                 # but the letters 'a' to 'f' in either case.
468                                 # This is because the character class contains
469                                 # all digits, and anything that isn't a
470                                 # hex digit, resulting in a class containing
471                                 # all characters, but the letters 'a' to 'f'
472                                 # and 'A' to 'F'.
473
474   Locale, Unicode and UTF-8
475       Some of the character classes have a somewhat different behaviour
476       depending on the internal encoding of the source string, and the locale
477       that is in effect.
478
479       "\w", "\d", "\s" and the POSIX character classes (and their negations,
480       including "\W", "\D", "\S") suffer from this behaviour.
481
482       The rule is that if the source string is in UTF-8 format, the character
483       classes match according to the Unicode properties. If the source string
484       isn't, then the character classes match according to whatever locale is
485       in effect. If there is no locale, they match the ASCII defaults (52
486       letters, 10 digits and underscore for "\w", 0 to 9 for "\d", etc).
487
488       This usually means that if you are matching against characters whose
489       "ord()" values are between 128 and 255 inclusive, your character class
490       may match or not depending on the current locale, and whether the
491       source string is in UTF-8 format. The string will be in UTF-8 format if
492       it contains characters whose "ord()" value exceeds 255. But a string
493       may be in UTF-8 format without it having such characters.
494
495       For portability reasons, it may be better to not use "\w", "\d", "\s"
496       or the POSIX character classes, and use the Unicode properties instead.
497
498       Examples
499
500        $str =  "\xDF";      # $str is not in UTF-8 format.
501        $str =~ /^\w/;       # No match, as $str isn't in UTF-8 format.
502        $str .= "\x{0e0b}";  # Now $str is in UTF-8 format.
503        $str =~ /^\w/;       # Match! $str is now in UTF-8 format.
504        chop $str;
505        $str =~ /^\w/;       # Still a match! $str remains in UTF-8 format.
506
507
508
509perl v5.10.1                      2009-05-14                PERLRECHARCLASS(1)
Impressum