This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
add 5.12.5 to perlhist
[perl5.git] / pod / perlrecharclass.pod
CommitLineData
8a118206 1=head1 NAME
ea449505 2X<character class>
8a118206
RGS
3
4perlrecharclass - Perl Regular Expression Character Classes
5
6=head1 DESCRIPTION
7
8The top level documentation about Perl regular expressions
9is found in L<perlre>.
10
11This manual page discusses the syntax and use of character
6b83a163 12classes in Perl regular expressions.
8a118206 13
6b83a163 14A character class is a way of denoting a set of characters
8a118206 15in such a way that one character of the set is matched.
6b83a163 16It's important to remember that: matching a character class
8a118206
RGS
17consumes exactly one character in the source string. (The source
18string is the string the regular expression is matched against.)
19
20There are three types of character classes in Perl regular
6b83a163 21expressions: the dot, backslash sequences, and the form enclosed in square
ea449505 22brackets. Keep in mind, though, that often the term "character class" is used
6b83a163 23to mean just the bracketed form. Certainly, most Perl documentation does that.
8a118206
RGS
24
25=head2 The dot
26
27The dot (or period), C<.> is probably the most used, and certainly
28the most well-known character class. By default, a dot matches any
5db9882c 29character, except for the newline. That default can be changed to
6b83a163
KW
30add matching the newline by using the I<single line> modifier: either
31for the entire regular expression with the C</s> modifier, or
32locally with C<(?s)>. (The experimental C<\N> backslash sequence, described
33below, matches any character except newline without regard to the
34I<single line> modifier.)
8a118206
RGS
35
36Here are some examples:
37
38 "a" =~ /./ # Match
39 "." =~ /./ # Match
40 "" =~ /./ # No match (dot has to match a character)
41 "\n" =~ /./ # No match (dot does not match a newline)
42 "\n" =~ /./s # Match (global 'single line' modifier)
43 "\n" =~ /(?s:.)/ # Match (local 'single line' modifier)
44 "ab" =~ /^.$/ # No match (dot matches one character)
45
6b83a163 46=head2 Backslash sequences
82206b5e 47X<\w> X<\W> X<\s> X<\S> X<\d> X<\D> X<\p> X<\P>
ea449505
KW
48X<\N> X<\v> X<\V> X<\h> X<\H>
49X<word> X<whitespace>
8a118206 50
6b83a163
KW
51A backslash sequence is a sequence of characters, the first one of which is a
52backslash. Perl ascribes special meaning to many such sequences, and some of
53these are character classes. That is, they match a single character each,
54provided that the character belongs to the specific set of characters defined
55by the sequence.
8a118206 56
6b83a163
KW
57Here's a list of the backslash sequences that are character classes. They
58are discussed in more detail below. (For the backslash sequences that aren't
59character classes, see L<perlrebackslash>.)
8a118206 60
6b83a163
KW
61 \d Match a decimal digit character.
62 \D Match a non-decimal-digit character.
8a118206
RGS
63 \w Match a "word" character.
64 \W Match a non-"word" character.
ea449505
KW
65 \s Match a whitespace character.
66 \S Match a non-whitespace character.
67 \h Match a horizontal whitespace character.
68 \H Match a character that isn't horizontal whitespace.
ea449505
KW
69 \v Match a vertical whitespace character.
70 \V Match a character that isn't vertical whitespace.
6b83a163
KW
71 \N Match a character that isn't a newline. Experimental.
72 \pP, \p{Prop} Match a character that has the given Unicode property.
6c5a041f 73 \PP, \P{Prop} Match a character that doesn't have the Unicode property
8a118206 74
1433f837
KW
75=head3 \N
76
77C<\N> is new in 5.12, and is experimental. It, like the dot, matches any
78character that is not a newline. The difference is that C<\N> is not influenced
79by the I<single line> regular expression modifier (see L</The dot> above). Note
80that the form C<\N{...}> may mean something completely different. When the
81C<{...}> is a L<quantifier|perlre/Quantifiers>, it means to match a non-newline
82character that many times. For example, C<\N{3}> means to match 3
83non-newlines; C<\N{5,}> means to match 5 or more non-newlines. But if C<{...}>
84is not a legal quantifier, it is presumed to be a named character. See
85L<charnames> for those. For example, none of C<\N{COLON}>, C<\N{4F}>, and
86C<\N{F4}> contain legal quantifiers, so Perl will try to find characters whose
87names are respectively C<COLON>, C<4F>, and C<F4>.
88
8a118206
RGS
89=head3 Digits
90
b6538e4f 91C<\d> matches a single character considered to be a decimal I<digit>.
5db9882c 92If the C</a> regular expression modifier is in effect, it matches [0-9].
582da942 93Otherwise, it
82206b5e
KW
94matches anything that is matched by C<\p{Digit}>, which includes [0-9].
95(An unlikely possible exception is that under locale matching rules, the
96current locale might not have [0-9] matched by C<\d>, and/or might match
97other characters whose code point is less than 256. Such a locale
98definition would be in violation of the C language standard, but Perl
99doesn't currently assume anything in regard to this.)
100
101What this means is that unless the C</a> modifier is in effect C<\d> not
102only matches the digits '0' - '9', but also Arabic, Devanagari, and
103digits from other languages. This may cause some confusion, and some
104security issues.
105
106Some digits that C<\d> matches look like some of the [0-9] ones, but
107have different values. For example, BENGALI DIGIT FOUR (U+09EA) looks
108very much like an ASCII DIGIT EIGHT (U+0038). An application that
109is expecting only the ASCII digits might be misled, or if the match is
110C<\d+>, the matched string might contain a mixture of digits from
111different writing systems that look like they signify a number different
67592e11 112than they actually do. L<Unicode::UCD/num()> can
e397bccf 113be used to safely
82206b5e
KW
114calculate the value, returning C<undef> if the input string contains
115such a mixture.
116
117What C<\p{Digit}> means (and hence C<\d> except under the C</a>
118modifier) is C<\p{General_Category=Decimal_Number}>, or synonymously,
119C<\p{General_Category=Digit}>. Starting with Unicode version 4.1, this
120is the same set of characters matched by C<\p{Numeric_Type=Decimal}>.
6b83a163
KW
121But Unicode also has a different property with a similar name,
122C<\p{Numeric_Type=Digit}>, which matches a completely different set of
82206b5e
KW
123characters. These characters are things such as C<CIRCLED DIGIT ONE>
124or subscripts, or are from writing systems that lack all ten digits.
6b83a163 125
82206b5e
KW
126The design intent is for C<\d> to exactly match the set of characters
127that can safely be used with "normal" big-endian positional decimal
128syntax, where, for example 123 means one 'hundred', plus two 'tens',
129plus three 'ones'. This positional notation does not necessarily apply
130to characters that match the other type of "digit",
131C<\p{Numeric_Type=Digit}>, and so C<\d> doesn't match them.
6b83a163 132
e2cfb18c 133The Tamil digits (U+0BE6 - U+0BEF) can also legally be
82206b5e
KW
134used in old-style Tamil numbers in which they would appear no more than
135one in a row, separated by characters that mean "times 10", "times 100",
136etc. (See L<http://www.unicode.org/notes/tn21>.)
8a118206 137
b6538e4f 138Any character not matched by C<\d> is matched by C<\D>.
8a118206
RGS
139
140=head3 Word characters
141
ea449505 142A C<\w> matches a single alphanumeric character (an alphabetic character, or a
d35dd6c6
KW
143decimal digit) or a connecting punctuation character, such as an
144underscore ("_"). It does not match a whole word. To match a whole
82206b5e 145word, use C<\w+>. This isn't the same thing as matching an English word, but
765fa144 146in the ASCII range it is the same as a string of Perl-identifier
82206b5e
KW
147characters.
148
149=over
150
151=item If the C</a> modifier is in effect ...
152
153C<\w> matches the 63 characters [a-zA-Z0-9_].
154
155=item otherwise ...
156
157=over
158
159=item For code points above 255 ...
160
161C<\w> matches the same as C<\p{Word}> matches in this range. That is,
162it matches Thai letters, Greek letters, etc. This includes connector
d35dd6c6 163punctuation (like the underscore) which connect two words together, or
b6538e4f 164diacritics, such as a C<COMBINING TILDE> and the modifier letters, which
82206b5e
KW
165are generally used to add auxiliary markings to letters.
166
167=item For code points below 256 ...
168
169=over
170
171=item if locale rules are in effect ...
172
173C<\w> matches the platform's native underscore character plus whatever
174the locale considers to be alphanumeric.
175
176=item if Unicode rules are in effect or if on an EBCDIC platform ...
177
178C<\w> matches exactly what C<\p{Word}> matches.
179
180=item otherwise ...
181
182C<\w> matches [a-zA-Z0-9_].
183
184=back
185
186=back
187
188=back
189
190Which rules apply are determined as described in L<perlre/Which character set modifier is in effect?>.
8a118206 191
6b83a163
KW
192There are a number of security issues with the full Unicode list of word
193characters. See L<http://unicode.org/reports/tr36>.
194
195Also, for a somewhat finer-grained set of characters that are in programming
196language identifiers beyond the ASCII range, you may wish to instead use the
e2cfb18c
KW
197more customized L</Unicode Properties>, C<\p{ID_Start}>,
198C<\p{ID_Continue}>, C<\p{XID_Start}>, and C<\p{XID_Continue}>. See
199L<http://unicode.org/reports/tr31>.
6b83a163 200
b6538e4f 201Any character not matched by C<\w> is matched by C<\W>.
8a118206 202
ea449505
KW
203=head3 Whitespace
204
82206b5e
KW
205C<\s> matches any single character considered whitespace.
206
207=over
208
209=item If the C</a> modifier is in effect ...
210
211C<\s> matches the 5 characters [\t\n\f\r ]; that is, the horizontal tab,
212the newline, the form feed, the carriage return, and the space. (Note
213that it doesn't match the vertical tab, C<\cK> on ASCII platforms.)
214
215=item otherwise ...
216
217=over
218
219=item For code points above 255 ...
220
221C<\s> matches exactly the code points above 255 shown with an "s" column
222in the table below.
223
224=item For code points below 256 ...
225
226=over
227
228=item if locale rules are in effect ...
229
230C<\s> matches whatever the locale considers to be whitespace. Note that
231this is likely to include the vertical space, unlike non-locale C<\s>
232matching.
233
234=item if Unicode rules are in effect or if on an EBCDIC platform ...
235
236C<\s> matches exactly the characters shown with an "s" column in the
237table below.
238
239=item otherwise ...
240
241C<\s> matches [\t\n\f\r ].
242Note that this list doesn't include the non-breaking space.
243
244=back
245
246=back
247
248=back
249
250Which rules apply are determined as described in L<perlre/Which character set modifier is in effect?>.
8a118206 251
b6538e4f 252Any character not matched by C<\s> is matched by C<\S>.
8a118206 253
b6538e4f 254C<\h> matches any character considered horizontal whitespace;
8129baca 255this includes the platform's space and tab characters and several others
b6538e4f 256listed in the table below. C<\H> matches any character
8129baca
KW
257not considered horizontal whitespace. They use the platform's native
258character set, and do not consider any locale that may otherwise be in
259use.
ea449505 260
b6538e4f 261C<\v> matches any character considered vertical whitespace;
8129baca 262this includes the platform's carriage return and line feed characters (newline)
b6538e4f
TC
263plus several other characters, all listed in the table below.
264C<\V> matches any character not considered vertical whitespace.
8129baca
KW
265They use the platform's native character set, and do not consider any
266locale that may otherwise be in use.
8a118206
RGS
267
268C<\R> matches anything that can be considered a newline under Unicode
269rules. It's not a character class, as it can match a multi-character
270sequence. Therefore, it cannot be used inside a bracketed character
8129baca
KW
271class; use C<\v> instead (vertical whitespace). It uses the platform's
272native character set, and does not consider any locale that may
273otherwise be in use.
ea449505 274Details are discussed in L<perlrebackslash>.
8a118206 275
82206b5e 276Note that unlike C<\s> (and C<\d> and C<\w>), C<\h> and C<\v> always match
8129baca
KW
277the same characters, without regard to other factors, such as the active
278locale or whether the source string is in UTF-8 format.
8a118206 279
82206b5e 280One might think that C<\s> is equivalent to C<[\h\v]>. This is not true.
5db9882c
KW
281The difference is that the vertical tab (C<"\x0b">) is not matched by
282C<\s>; it is however considered vertical whitespace.
8a118206
RGS
283
284The following table is a complete listing of characters matched by
82206b5e 285C<\s>, C<\h> and C<\v> as of Unicode 6.0.
8a118206 286
582da942 287The first column gives the Unicode code point of the character (in hex format),
8a118206 288the second column gives the (Unicode) name. The third column indicates
ea449505
KW
289by which class(es) the character is matched (assuming no locale or EBCDIC code
290page is in effect that changes the C<\s> matching).
8a118206 291
fc28d2a3
KW
292 0x0009 CHARACTER TABULATION h s
293 0x000a LINE FEED (LF) vs
294 0x000b LINE TABULATION v
295 0x000c FORM FEED (FF) vs
296 0x000d CARRIAGE RETURN (CR) vs
297 0x0020 SPACE h s
298 0x0085 NEXT LINE (NEL) vs [1]
299 0x00a0 NO-BREAK SPACE h s [1]
300 0x1680 OGHAM SPACE MARK h s
301 0x180e MONGOLIAN VOWEL SEPARATOR h s
302 0x2000 EN QUAD h s
303 0x2001 EM QUAD h s
304 0x2002 EN SPACE h s
305 0x2003 EM SPACE h s
306 0x2004 THREE-PER-EM SPACE h s
307 0x2005 FOUR-PER-EM SPACE h s
308 0x2006 SIX-PER-EM SPACE h s
309 0x2007 FIGURE SPACE h s
310 0x2008 PUNCTUATION SPACE h s
311 0x2009 THIN SPACE h s
312 0x200a HAIR SPACE h s
313 0x2028 LINE SEPARATOR vs
314 0x2029 PARAGRAPH SEPARATOR vs
315 0x202f NARROW NO-BREAK SPACE h s
316 0x205f MEDIUM MATHEMATICAL SPACE h s
317 0x3000 IDEOGRAPHIC SPACE h s
8a118206
RGS
318
319=over 4
320
321=item [1]
322
82206b5e
KW
323NEXT LINE and NO-BREAK SPACE may or may not match C<\s> depending
324on the rules in effect. See
325L<the beginning of this section|/Whitespace>.
8a118206
RGS
326
327=back
328
8a118206
RGS
329=head3 Unicode Properties
330
c1c4ae3a
KW
331C<\pP> and C<\p{Prop}> are character classes to match characters that fit given
332Unicode properties. One letter property names can be used in the C<\pP> form,
333with the property name following the C<\p>, otherwise, braces are required.
334When using braces, there is a single form, which is just the property name
335enclosed in the braces, and a compound form which looks like C<\p{name=value}>,
b6538e4f 336which means to match if the property "name" for the character has that particular
c1c4ae3a 337"value".
e1b711da
KW
338For instance, a match for a number can be written as C</\pN/> or as
339C</\p{Number}/>, or as C</\p{Number=True}/>.
340Lowercase letters are matched by the property I<Lowercase_Letter> which
e2cfb18c 341has the short form I<Ll>. They need the braces, so are written as C</\p{Ll}/> or
e1b711da
KW
342C</\p{Lowercase_Letter}/>, or C</\p{General_Category=Lowercase_Letter}/>
343(the underscores are optional).
344C</\pLl/> is valid, but means something different.
8a118206
RGS
345It matches a two character string: a letter (Unicode property C<\pL>),
346followed by a lowercase C<l>.
347
bc943be5 348If locale rules are not in effect, the use of
82206b5e 349a Unicode property will force the regular expression into using Unicode
bc943be5 350rules, if it isn't already.
82206b5e 351
56ca34ca
KW
352Note that almost all properties are immune to case-insensitive matching.
353That is, adding a C</i> regular expression modifier does not change what
82206b5e 354they match. There are two sets that are affected. The first set is
56ca34ca
KW
355C<Uppercase_Letter>,
356C<Lowercase_Letter>,
357and C<Titlecase_Letter>,
358all of which match C<Cased_Letter> under C</i> matching.
b6538e4f 359The second set is
56ca34ca
KW
360C<Uppercase>,
361C<Lowercase>,
362and C<Titlecase>,
363all of which match C<Cased> under C</i> matching.
364(The difference between these sets is that some things, such as Roman
e2cfb18c 365numerals, come in both upper and lower case, so they are C<Cased>, but
b6538e4f 366aren't considered to be letters, so they aren't C<Cased_Letter>s. They're
82206b5e
KW
367actually C<Letter_Number>s.)
368This set also includes its subsets C<PosixUpper> and C<PosixLower>, both
e2cfb18c 369of which under C</i> match C<PosixAlpha>.
56ca34ca
KW
370
371For more details on Unicode properties, see L<perlunicode/Unicode
372Character Properties>; for a
e1b711da 373complete list of possible properties, see
56ca34ca
KW
374L<perluniprops/Properties accessible through \p{} and \P{}>,
375which notes all forms that have C</i> differences.
e1b711da 376It is also possible to define your own properties. This is discussed in
8a118206
RGS
377L<perlunicode/User-Defined Character Properties>.
378
94b42e47
KW
379Unicode properties are defined (surprise!) only on Unicode code points.
380A warning is raised and all matches fail on non-Unicode code points
381(those above the legal Unicode maximum of 0x10FFFF). This can be
382somewhat surprising,
383
384 chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails.
385 chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Also fails!
386
387Even though these two matches might be thought of as complements, they
388are so only on Unicode code points.
389
8a118206
RGS
390=head4 Examples
391
392 "a" =~ /\w/ # Match, "a" is a 'word' character.
393 "7" =~ /\w/ # Match, "7" is a 'word' character as well.
394 "a" =~ /\d/ # No match, "a" isn't a digit.
395 "7" =~ /\d/ # Match, "7" is a digit.
ea449505 396 " " =~ /\s/ # Match, a space is whitespace.
8a118206
RGS
397 "a" =~ /\D/ # Match, "a" is a non-digit.
398 "7" =~ /\D/ # No match, "7" is not a non-digit.
ea449505 399 " " =~ /\S/ # No match, a space is not non-whitespace.
8a118206 400
ea449505
KW
401 " " =~ /\h/ # Match, space is horizontal whitespace.
402 " " =~ /\v/ # No match, space is not vertical whitespace.
403 "\r" =~ /\v/ # Match, a return is vertical whitespace.
8a118206
RGS
404
405 "a" =~ /\pL/ # Match, "a" is a letter.
406 "a" =~ /\p{Lu}/ # No match, /\p{Lu}/ matches upper case letters.
407
408 "\x{0e0b}" =~ /\p{Thai}/ # Match, \x{0e0b} is the character
409 # 'THAI CHARACTER SO SO', and that's in
410 # Thai Unicode class.
ea449505 411 "a" =~ /\P{Lao}/ # Match, as "a" is not a Laotian character.
8a118206 412
82206b5e
KW
413It is worth emphasizing that C<\d>, C<\w>, etc, match single characters, not
414complete numbers or words. To match a number (that consists of digits),
415use C<\d+>; to match a word, use C<\w+>. But be aware of the security
416considerations in doing so, as mentioned above.
8a118206
RGS
417
418=head2 Bracketed Character Classes
419
420The third form of character class you can use in Perl regular expressions
6b83a163 421is the bracketed character class. In its simplest form, it lists the characters
c1c4ae3a 422that may be matched, surrounded by square brackets, like this: C<[aeiou]>.
ea449505 423This matches one of C<a>, C<e>, C<i>, C<o> or C<u>. Like the other
1f59b283 424character classes, exactly one character is matched.* To match
ea449505 425a longer string consisting of characters mentioned in the character
6b83a163 426class, follow the character class with a L<quantifier|perlre/Quantifiers>. For
b6538e4f 427instance, C<[aeiou]+> matches one or more lowercase English vowels.
8a118206
RGS
428
429Repeating a character in a character class has no
430effect; it's considered to be in the set only once.
431
432Examples:
433
434 "e" =~ /[aeiou]/ # Match, as "e" is listed in the class.
435 "p" =~ /[aeiou]/ # No match, "p" is not listed in the class.
436 "ae" =~ /^[aeiou]$/ # No match, a character class only matches
437 # a single character.
438 "ae" =~ /^[aeiou]+$/ # Match, due to the quantifier.
439
1f59b283
KW
440 -------
441
df0e3973 442* There is an exception to a bracketed character class matching a
1cecf2c0 443single character only. When the class is to match caselessly under C</i>
9d53c457
KW
444matching rules, and a character that is explicitly mentioned inside the
445class matches a
1f59b283
KW
446multiple-character sequence caselessly under Unicode rules, the class
447(when not L<inverted|/Negation>) will also match that sequence. For
448example, Unicode says that the letter C<LATIN SMALL LETTER SHARP S>
449should match the sequence C<ss> under C</i> rules. Thus,
450
451 'ss' =~ /\A\N{LATIN SMALL LETTER SHARP S}\z/i # Matches
452 'ss' =~ /\A[aeioust\N{LATIN SMALL LETTER SHARP S}]\z/i # Matches
453
9d53c457
KW
454For this to happen, the character must be explicitly specified, and not
455be part of a multi-character range (not even as one of its endpoints).
456(L</Character Ranges> will be explained shortly.) Therefore,
457
458 'ss' =~ /\A[\0-\x{ff}]\z/i # Doesn't match
459 'ss' =~ /\A[\0-\N{LATIN SMALL LETTER SHARP S}]\z/i # No match
460 'ss' =~ /\A[\xDF-\xDF]\z/i # Matches on ASCII platforms, since \XDF
461 # is LATIN SMALL LETTER SHARP S, and the
462 # range is just a single element
463
464Note that it isn't a good idea to specify these types of ranges anyway.
465
8a118206
RGS
466=head3 Special Characters Inside a Bracketed Character Class
467
468Most characters that are meta characters in regular expressions (that
df225385 469is, characters that carry a special meaning like C<.>, C<*>, or C<(>) lose
8a118206
RGS
470their special meaning and can be used inside a character class without
471the need to escape them. For instance, C<[()]> matches either an opening
472parenthesis, or a closing parenthesis, and the parens inside the character
473class don't group or capture.
474
475Characters that may carry a special meaning inside a character class are:
476C<\>, C<^>, C<->, C<[> and C<]>, and are discussed below. They can be
477escaped with a backslash, although this is sometimes not needed, in which
478case the backslash may be omitted.
479
480The sequence C<\b> is special inside a bracketed character class. While
6b83a163 481outside the character class, C<\b> is an assertion indicating a point
8a118206
RGS
482that does not have either two word characters or two non-word characters
483on either side, inside a bracketed character class, C<\b> matches a
484backspace character.
485
df225385
KW
486The sequences
487C<\a>,
488C<\c>,
489C<\e>,
490C<\f>,
491C<\n>,
e526e8bb 492C<\N{I<NAME>}>,
765fa144 493C<\N{U+I<hex char>}>,
df225385
KW
494C<\r>,
495C<\t>,
496and
497C<\x>
06ee63cd
KW
498are also special and have the same meanings as they do outside a
499bracketed character class. (However, inside a bracketed character
500class, if C<\N{I<NAME>}> expands to a sequence of characters, only the first
501one in the sequence is used, with a warning.)
df225385 502
ea449505
KW
503Also, a backslash followed by two or three octal digits is considered an octal
504number.
df225385 505
6b83a163
KW
506A C<[> is not special inside a character class, unless it's the start of a
507POSIX character class (see L</POSIX Character Classes> below). It normally does
508not need escaping.
8a118206 509
6b83a163
KW
510A C<]> is normally either the end of a POSIX character class (see
511L</POSIX Character Classes> below), or it signals the end of the bracketed
512character class. If you want to include a C<]> in the set of characters, you
513must generally escape it.
b6538e4f 514
8a118206
RGS
515However, if the C<]> is the I<first> (or the second if the first
516character is a caret) character of a bracketed character class, it
517does not denote the end of the class (as you cannot have an empty class)
518and is considered part of the set of characters that can be matched without
519escaping.
520
521Examples:
522
523 "+" =~ /[+?*]/ # Match, "+" in a character class is not special.
524 "\cH" =~ /[\b]/ # Match, \b inside in a character class
c1c4ae3a 525 # is equivalent to a backspace.
8a118206
RGS
526 "]" =~ /[][]/ # Match, as the character class contains.
527 # both [ and ].
528 "[]" =~ /[[]]/ # Match, the pattern contains a character class
529 # containing just ], and the character class is
530 # followed by a ].
531
532=head3 Character Ranges
533
534It is not uncommon to want to match a range of characters. Luckily, instead
b6538e4f 535of listing all characters in the range, one may use the hyphen (C<->).
8a118206 536If inside a bracketed character class you have two characters separated
b6538e4f 537by a hyphen, it's treated as if all characters between the two were in
8a118206 538the class. For instance, C<[0-9]> matches any ASCII digit, and C<[a-m]>
e2cfb18c 539matches any lowercase letter from the first half of the ASCII alphabet.
8a118206
RGS
540
541Note that the two characters on either side of the hyphen are not
765fa144 542necessarily both letters or both digits. Any character is possible,
8a118206 543although not advisable. C<['-?]> contains a range of characters, but
b6538e4f 544most people will not know which characters that means. Furthermore,
8a118206
RGS
545such ranges may lead to portability problems if the code has to run on
546a platform that uses a different character set, such as EBCDIC.
547
ea449505
KW
548If a hyphen in a character class cannot syntactically be part of a range, for
549instance because it is the first or the last character of the character class,
b6538e4f
TC
550or if it immediately follows a range, the hyphen isn't special, and so is
551considered a character to be matched literally. If you want a hyphen in
552your set of characters to be matched and its position in the class is such
553that it could be considered part of a range, you must escape that hyphen
554with a backslash.
8a118206
RGS
555
556Examples:
557
558 [a-z] # Matches a character that is a lower case ASCII letter.
c1c4ae3a
KW
559 [a-fz] # Matches any letter between 'a' and 'f' (inclusive) or
560 # the letter 'z'.
8a118206
RGS
561 [-z] # Matches either a hyphen ('-') or the letter 'z'.
562 [a-f-m] # Matches any letter between 'a' and 'f' (inclusive), the
563 # hyphen ('-'), or the letter 'm'.
564 ['-?] # Matches any of the characters '()*+,-./0123456789:;<=>?
565 # (But not on an EBCDIC platform).
566
567
568=head3 Negation
569
570It is also possible to instead list the characters you do not want to
571match. You can do so by using a caret (C<^>) as the first character in the
b6538e4f 572character class. For instance, C<[^a-z]> matches any character that is not a
e2cfb18c
KW
573lowercase ASCII letter, which therefore includes more than a million
574Unicode code points. The class is said to be "negated" or "inverted".
8a118206
RGS
575
576This syntax make the caret a special character inside a bracketed character
577class, but only if it is the first character of the class. So if you want
82206b5e 578the caret as one of the characters to match, either escape the caret or
e2cfb18c 579else don't list it first.
8a118206 580
1f59b283 581In inverted bracketed character classes, Perl ignores the Unicode rules
56e1c5aa
KW
582that normally say that certain characters should match a sequence of
583multiple characters under caseless C</i> matching. Following those
584rules could lead to highly confusing situations:
1f59b283 585
582da942 586 "ss" =~ /^[^\xDF]+$/ui; # Matches!
1f59b283
KW
587
588This should match any sequences of characters that aren't C<\xDF> nor
589what C<\xDF> matches under C</i>. C<"s"> isn't C<\xDF>, but Unicode
590says that C<"ss"> is what C<\xDF> matches under C</i>. So which one
591"wins"? Do you fail the match because the string has C<ss> or accept it
582da942
KW
592because it has an C<s> followed by another C<s>? Perl has chosen the
593latter.
1f59b283 594
8a118206
RGS
595Examples:
596
597 "e" =~ /[^aeiou]/ # No match, the 'e' is listed.
598 "x" =~ /[^aeiou]/ # Match, as 'x' isn't a lowercase vowel.
599 "^" =~ /[^^]/ # No match, matches anything that isn't a caret.
600 "^" =~ /[x^]/ # Match, caret is not special here.
601
602=head3 Backslash Sequences
603
ea449505 604You can put any backslash sequence character class (with the exception of
765fa144 605C<\N> and C<\R>) inside a bracketed character class, and it will act just
b6538e4f
TC
606as if you had put all characters matched by the backslash sequence inside the
607character class. For instance, C<[a-f\d]> matches any decimal digit, or any
6b83a163
KW
608of the lowercase letters between 'a' and 'f' inclusive.
609
610C<\N> within a bracketed character class must be of the forms C<\N{I<name>}>
765fa144 611or C<\N{U+I<hex char>}>, and NOT be the form that matches non-newlines,
6b83a163
KW
612for the same reason that a dot C<.> inside a bracketed character class loses
613its special meaning: it matches nearly anything, which generally isn't what you
614want to happen.
df225385 615
8a118206
RGS
616
617Examples:
618
619 /[\p{Thai}\d]/ # Matches a character that is either a Thai
620 # character, or a digit.
621 /[^\p{Arabic}()]/ # Matches a character that is neither an Arabic
622 # character, nor a parenthesis.
623
624Backslash sequence character classes cannot form one of the endpoints
6b83a163
KW
625of a range. Thus, you can't say:
626
627 /[\p{Thai}-\d]/ # Wrong!
8a118206 628
6b83a163 629=head3 POSIX Character Classes
ea449505 630X<character class> X<\p> X<\p{}>
ea449505
KW
631X<alpha> X<alnum> X<ascii> X<blank> X<cntrl> X<digit> X<graph>
632X<lower> X<print> X<punct> X<space> X<upper> X<word> X<xdigit>
8a118206 633
6b83a163
KW
634POSIX character classes have the form C<[:class:]>, where I<class> is
635name, and the C<[:> and C<:]> delimiters. POSIX character classes only appear
8a118206 636I<inside> bracketed character classes, and are a convenient and descriptive
82206b5e 637way of listing a group of characters.
6b83a163
KW
638
639Be careful about the syntax,
8a118206
RGS
640
641 # Correct:
642 $string =~ /[[:alpha:]]/
643
644 # Incorrect (will warn):
645 $string =~ /[:alpha:]/
646
647The latter pattern would be a character class consisting of a colon,
648and the letters C<a>, C<l>, C<p> and C<h>.
82206b5e 649POSIX character classes can be part of a larger bracketed character class.
b6538e4f 650For example,
ea449505
KW
651
652 [01[:alpha:]%]
653
654is valid and matches '0', '1', any alphabetic character, and the percent sign.
8a118206
RGS
655
656Perl recognizes the following POSIX character classes:
657
ea449505 658 alpha Any alphabetical character ("[A-Za-z]").
b6538e4f 659 alnum Any alphanumeric character. ("[A-Za-z0-9]")
ea449505 660 ascii Any character in the ASCII character set.
ea8b8ad2 661 blank A GNU extension, equal to a space or a horizontal tab ("\t").
ea449505
KW
662 cntrl Any control character. See Note [2] below.
663 digit Any decimal digit ("[0-9]"), equivalent to "\d".
664 graph Any printable character, excluding a space. See Note [3] below.
665 lower Any lowercase character ("[a-z]").
666 print Any printable character, including a space. See Note [4] below.
c1c4ae3a 667 punct Any graphical character excluding "word" characters. Note [5].
ea449505
KW
668 space Any whitespace character. "\s" plus the vertical tab ("\cK").
669 upper Any uppercase character ("[A-Z]").
670 word A Perl extension ("[A-Za-z0-9_]"), equivalent to "\w".
671 xdigit Any hexadecimal digit ("[0-9a-fA-F]").
672
673Most POSIX character classes have two Unicode-style C<\p> property
674counterparts. (They are not official Unicode properties, but Perl extensions
675derived from official Unicode properties.) The table below shows the relation
676between POSIX character classes and these counterparts.
677
678One counterpart, in the column labelled "ASCII-range Unicode" in
b6538e4f 679the table, matches only characters in the ASCII character set.
ea449505
KW
680
681The other counterpart, in the column labelled "Full-range Unicode", matches any
682appropriate characters in the full Unicode character set. For example,
b6538e4f 683C<\p{Alpha}> matches not just the ASCII alphabetic characters, but any
82206b5e 684character in the entire Unicode character set considered alphabetic.
582da942 685An entry in the column labelled "backslash sequence" is a (short)
5db9882c 686equivalent.
ea449505 687
cbc24f92
KW
688 [[:...:]] ASCII-range Full-range backslash Note
689 Unicode Unicode sequence
ea449505 690 -----------------------------------------------------
cbc24f92
KW
691 alpha \p{PosixAlpha} \p{XPosixAlpha}
692 alnum \p{PosixAlnum} \p{XPosixAlnum}
82206b5e 693 ascii \p{ASCII}
cbc24f92
KW
694 blank \p{PosixBlank} \p{XPosixBlank} \h [1]
695 or \p{HorizSpace} [1]
696 cntrl \p{PosixCntrl} \p{XPosixCntrl} [2]
697 digit \p{PosixDigit} \p{XPosixDigit} \d
698 graph \p{PosixGraph} \p{XPosixGraph} [3]
699 lower \p{PosixLower} \p{XPosixLower}
700 print \p{PosixPrint} \p{XPosixPrint} [4]
701 punct \p{PosixPunct} \p{XPosixPunct} [5]
702 \p{PerlSpace} \p{XPerlSpace} \s [6]
703 space \p{PosixSpace} \p{XPosixSpace} [6]
704 upper \p{PosixUpper} \p{XPosixUpper}
705 word \p{PosixWord} \p{XPosixWord} \w
82206b5e 706 xdigit \p{PosixXDigit} \p{XPosixXDigit}
8a118206
RGS
707
708=over 4
709
ea449505
KW
710=item [1]
711
712C<\p{Blank}> and C<\p{HorizSpace}> are synonyms.
713
714=item [2]
8a118206 715
ea449505 716Control characters don't produce output as such, but instead usually control
b6538e4f 717the terminal somehow: for example, newline and backspace are control characters.
82206b5e 718In the ASCII range, characters whose code points are between 0 and 31 inclusive,
ea449505 719plus 127 (C<DEL>) are control characters.
8a118206 720
c1c4ae3a
KW
721On EBCDIC platforms, it is likely that the code page will define C<[[:cntrl:]]>
722to be the EBCDIC equivalents of the ASCII controls, plus the controls
bc943be5 723that in Unicode have code points from 128 through 159.
ea449505
KW
724
725=item [3]
8a118206
RGS
726
727Any character that is I<graphical>, that is, visible. This class consists
b6538e4f 728of all alphanumeric characters and all punctuation characters.
8a118206 729
ea449505 730=item [4]
8a118206 731
b6538e4f
TC
732All printable characters, which is the set of all graphical characters
733plus those whitespace characters which are not also controls.
ea449505 734
b6dac59a 735=item [5]
ea449505 736
b6538e4f 737C<\p{PosixPunct}> and C<[[:punct:]]> in the ASCII range match all
ea449505
KW
738non-controls, non-alphanumeric, non-space characters:
739C<[-!"#$%&'()*+,./:;<=E<gt>?@[\\\]^_`{|}~]> (although if a locale is in effect,
740it could alter the behavior of C<[[:punct:]]>).
741
cbc24f92
KW
742The similarly named property, C<\p{Punct}>, matches a somewhat different
743set in the ASCII range, namely
0be9b861
KW
744C<[-!"#%&'()*,./:;?@[\\\]_{}]>. That is, it is missing the nine
745characters C<[$+E<lt>=E<gt>^`|~]>.
6c5a041f
KW
746This is because Unicode splits what POSIX considers to be punctuation into two
747categories, Punctuation and Symbols.
748
e2cfb18c 749C<\p{XPosixPunct}> and (under Unicode rules) C<[[:punct:]]>, match what
765fa144
KW
750C<\p{PosixPunct}> matches in the ASCII range, plus what C<\p{Punct}>
751matches. This is different than strictly matching according to
752C<\p{Punct}>. Another way to say it is that
82206b5e
KW
753if Unicode rules are in effect, C<[[:punct:]]> matches all characters
754that Unicode considers punctuation, plus all ASCII-range characters that
755Unicode considers symbols.
8a118206 756
ea449505 757=item [6]
8a118206 758
82206b5e
KW
759C<\p{SpacePerl}> and C<\p{Space}> differ only in that in non-locale
760matching, C<\p{Space}> additionally
ea449505 761matches the vertical tab, C<\cK>. Same for the two ASCII-only range forms.
8a118206
RGS
762
763=back
764
ab6199be
KW
765There are various other synonyms that can be used besides the names
766listed in the table. For example, C<\p{PosixAlpha}> can be written as
767C<\p{Alpha}>. All are listed in
768L<perluniprops/Properties accessible through \p{} and \P{}>,
769plus all characters matched by each ASCII-range property.
770
771Both the C<\p> counterparts always assume Unicode rules are in effect.
772On ASCII platforms, this means they assume that the code points from 128
773to 255 are Latin-1, and that means that using them under locale rules is
774unwise unless the locale is guaranteed to be Latin-1 or UTF-8. In contrast, the
775POSIX character classes are useful under locale rules. They are
776affected by the actual rules in effect, as follows:
777
778=over
779
780=item If the C</a> modifier, is in effect ...
781
782Each of the POSIX classes matches exactly the same as their ASCII-range
783counterparts.
784
785=item otherwise ...
786
787=over
788
789=item For code points above 255 ...
790
791The POSIX class matches the same as its Full-range counterpart.
792
793=item For code points below 256 ...
794
795=over
796
797=item if locale rules are in effect ...
798
8129baca
KW
799The POSIX class matches according to the locale, except that
800C<word> uses the platform's native underscore character, no matter what
801the locale is.
ab6199be
KW
802
803=item if Unicode rules are in effect or if on an EBCDIC platform ...
804
805The POSIX class matches the same as the Full-range counterpart.
806
807=item otherwise ...
808
809The POSIX class matches the same as the ASCII range counterpart.
810
811=back
812
813=back
814
815=back
816
817Which rules apply are determined as described in
818L<perlre/Which character set modifier is in effect?>.
819
820It is proposed to change this behavior in a future release of Perl so that
821whether or not Unicode rules are in effect would not change the
822behavior: Outside of locale or an EBCDIC code page, the POSIX classes
823would behave like their ASCII-range counterparts. If you wish to
824comment on this proposal, send email to C<perl5-porters@perl.org>.
cbc24f92 825
1f59b283 826=head4 Negation of POSIX character classes
ea449505 827X<character class, negation>
8a118206
RGS
828
829A Perl extension to the POSIX character class is the ability to
830negate it. This is done by prefixing the class name with a caret (C<^>).
831Some examples:
832
ea449505
KW
833 POSIX ASCII-range Full-range backslash
834 Unicode Unicode sequence
835 -----------------------------------------------------
cbc24f92
KW
836 [[:^digit:]] \P{PosixDigit} \P{XPosixDigit} \D
837 [[:^space:]] \P{PosixSpace} \P{XPosixSpace}
838 \P{PerlSpace} \P{XPerlSpace} \S
839 [[:^word:]] \P{PerlWord} \P{XPosixWord} \W
840
765fa144 841The backslash sequence can mean either ASCII- or Full-range Unicode,
82206b5e 842depending on various factors as described in L<perlre/Which character set modifier is in effect?>.
8a118206
RGS
843
844=head4 [= =] and [. .]
845
b6538e4f 846Perl recognizes the POSIX character classes C<[=class=]> and
82206b5e 847C<[.class.]>, but does not (yet?) support them. Any attempt to use
b6538e4f 848either construct raises an exception.
8a118206
RGS
849
850=head4 Examples
851
852 /[[:digit:]]/ # Matches a character that is a digit.
853 /[01[:lower:]]/ # Matches a character that is either a
854 # lowercase letter, or '0' or '1'.
c1c4ae3a 855 /[[:digit:][:^xdigit:]]/ # Matches a character that can be anything
bc943be5
KW
856 # except the letters 'a' to 'f' and 'A' to
857 # 'F'. This is because the main character
858 # class is composed of two POSIX character
859 # classes that are ORed together, one that
860 # matches any digit, and the other that
861 # matches anything that isn't a hex digit.
862 # The OR adds the digits, leaving only the
863 # letters 'a' to 'f' and 'A' to 'F' excluded.