This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
PerlIO::Via: check arg is non-NULL before using it.
[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
4a88d526 30add matching the newline by using the I<single line> modifier:
6b83a163 31for the entire regular expression with the C</s> modifier, or
4a88d526
KW
32locally with C<(?s)> (and even globally within the scope of
33L<C<use re '/s'>|re/'E<sol>flags' mode>). (The C<L</\N>> backslash
34sequence, described
6b83a163
KW
35below, matches any character except newline without regard to the
36I<single line> modifier.)
8a118206
RGS
37
38Here are some examples:
39
40 "a" =~ /./ # Match
41 "." =~ /./ # Match
42 "" =~ /./ # No match (dot has to match a character)
43 "\n" =~ /./ # No match (dot does not match a newline)
44 "\n" =~ /./s # Match (global 'single line' modifier)
45 "\n" =~ /(?s:.)/ # Match (local 'single line' modifier)
46 "ab" =~ /^.$/ # No match (dot matches one character)
47
6b83a163 48=head2 Backslash sequences
82206b5e 49X<\w> X<\W> X<\s> X<\S> X<\d> X<\D> X<\p> X<\P>
ea449505
KW
50X<\N> X<\v> X<\V> X<\h> X<\H>
51X<word> X<whitespace>
8a118206 52
6b83a163
KW
53A backslash sequence is a sequence of characters, the first one of which is a
54backslash. Perl ascribes special meaning to many such sequences, and some of
55these are character classes. That is, they match a single character each,
56provided that the character belongs to the specific set of characters defined
57by the sequence.
8a118206 58
6b83a163
KW
59Here's a list of the backslash sequences that are character classes. They
60are discussed in more detail below. (For the backslash sequences that aren't
61character classes, see L<perlrebackslash>.)
8a118206 62
6b83a163
KW
63 \d Match a decimal digit character.
64 \D Match a non-decimal-digit character.
8a118206
RGS
65 \w Match a "word" character.
66 \W Match a non-"word" character.
ea449505
KW
67 \s Match a whitespace character.
68 \S Match a non-whitespace character.
69 \h Match a horizontal whitespace character.
70 \H Match a character that isn't horizontal whitespace.
ea449505
KW
71 \v Match a vertical whitespace character.
72 \V Match a character that isn't vertical whitespace.
4e5e0888 73 \N Match a character that isn't a newline.
6b83a163 74 \pP, \p{Prop} Match a character that has the given Unicode property.
6c5a041f 75 \PP, \P{Prop} Match a character that doesn't have the Unicode property
8a118206 76
1433f837
KW
77=head3 \N
78
2171640d 79C<\N>, available starting in v5.12, like the dot, matches any
1433f837
KW
80character that is not a newline. The difference is that C<\N> is not influenced
81by the I<single line> regular expression modifier (see L</The dot> above). Note
82that the form C<\N{...}> may mean something completely different. When the
83C<{...}> is a L<quantifier|perlre/Quantifiers>, it means to match a non-newline
84character that many times. For example, C<\N{3}> means to match 3
85non-newlines; C<\N{5,}> means to match 5 or more non-newlines. But if C<{...}>
86is not a legal quantifier, it is presumed to be a named character. See
87L<charnames> for those. For example, none of C<\N{COLON}>, C<\N{4F}>, and
88C<\N{F4}> contain legal quantifiers, so Perl will try to find characters whose
89names are respectively C<COLON>, C<4F>, and C<F4>.
90
8a118206
RGS
91=head3 Digits
92
b6538e4f 93C<\d> matches a single character considered to be a decimal I<digit>.
5db9882c 94If the C</a> regular expression modifier is in effect, it matches [0-9].
582da942 95Otherwise, it
82206b5e
KW
96matches anything that is matched by C<\p{Digit}>, which includes [0-9].
97(An unlikely possible exception is that under locale matching rules, the
d66e1f56
KW
98current locale might not have C<[0-9]> matched by C<\d>, and/or might match
99other characters whose code point is less than 256. The only such locale
100definitions that are legal would be to match C<[0-9]> plus another set of
10110 consecutive digit characters; anything else would be in violation of
102the C language standard, but Perl doesn't currently assume anything in
103regard to this.)
82206b5e
KW
104
105What this means is that unless the C</a> modifier is in effect C<\d> not
106only matches the digits '0' - '9', but also Arabic, Devanagari, and
107digits from other languages. This may cause some confusion, and some
108security issues.
109
110Some digits that C<\d> matches look like some of the [0-9] ones, but
111have different values. For example, BENGALI DIGIT FOUR (U+09EA) looks
8350b274
KW
112very much like an ASCII DIGIT EIGHT (U+0038), and LEPCHA DIGIT SIX
113(U+1C46) looks very much like an ASCII DIGIT FIVE (U+0035). An
114application that
82206b5e
KW
115is expecting only the ASCII digits might be misled, or if the match is
116C<\d+>, the matched string might contain a mixture of digits from
117different writing systems that look like they signify a number different
67592e11 118than they actually do. L<Unicode::UCD/num()> can
e397bccf 119be used to safely
82206b5e 120calculate the value, returning C<undef> if the input string contains
8350b274
KW
121such a mixture. Otherwise, for example, a displayed price might be
122deliberately different than it appears.
82206b5e
KW
123
124What C<\p{Digit}> means (and hence C<\d> except under the C</a>
125modifier) is C<\p{General_Category=Decimal_Number}>, or synonymously,
126C<\p{General_Category=Digit}>. Starting with Unicode version 4.1, this
127is the same set of characters matched by C<\p{Numeric_Type=Decimal}>.
6b83a163
KW
128But Unicode also has a different property with a similar name,
129C<\p{Numeric_Type=Digit}>, which matches a completely different set of
82206b5e
KW
130characters. These characters are things such as C<CIRCLED DIGIT ONE>
131or subscripts, or are from writing systems that lack all ten digits.
6b83a163 132
82206b5e
KW
133The design intent is for C<\d> to exactly match the set of characters
134that can safely be used with "normal" big-endian positional decimal
135syntax, where, for example 123 means one 'hundred', plus two 'tens',
136plus three 'ones'. This positional notation does not necessarily apply
137to characters that match the other type of "digit",
138C<\p{Numeric_Type=Digit}>, and so C<\d> doesn't match them.
6b83a163 139
e2cfb18c 140The Tamil digits (U+0BE6 - U+0BEF) can also legally be
82206b5e
KW
141used in old-style Tamil numbers in which they would appear no more than
142one in a row, separated by characters that mean "times 10", "times 100",
143etc. (See L<http://www.unicode.org/notes/tn21>.)
8a118206 144
b6538e4f 145Any character not matched by C<\d> is matched by C<\D>.
8a118206
RGS
146
147=head3 Word characters
148
ea449505 149A C<\w> matches a single alphanumeric character (an alphabetic character, or a
41805eb9
KW
150decimal digit); or a connecting punctuation character, such as an
151underscore ("_"); or a "mark" character (like some sort of accent) that
152attaches to one of those. It does not match a whole word. To match a
153whole word, use C<\w+>. This isn't the same thing as matching an
154English word, but in the ASCII range it is the same as a string of
155Perl-identifier characters.
82206b5e
KW
156
157=over
158
159=item If the C</a> modifier is in effect ...
160
161C<\w> matches the 63 characters [a-zA-Z0-9_].
162
163=item otherwise ...
164
165=over
166
167=item For code points above 255 ...
168
169C<\w> matches the same as C<\p{Word}> matches in this range. That is,
170it matches Thai letters, Greek letters, etc. This includes connector
d35dd6c6 171punctuation (like the underscore) which connect two words together, or
b6538e4f 172diacritics, such as a C<COMBINING TILDE> and the modifier letters, which
82206b5e
KW
173are generally used to add auxiliary markings to letters.
174
175=item For code points below 256 ...
176
177=over
178
179=item if locale rules are in effect ...
180
181C<\w> matches the platform's native underscore character plus whatever
182the locale considers to be alphanumeric.
183
04c2d19c 184=item if, instead, Unicode rules are in effect ...
82206b5e
KW
185
186C<\w> matches exactly what C<\p{Word}> matches.
187
188=item otherwise ...
189
190C<\w> matches [a-zA-Z0-9_].
191
192=back
193
194=back
195
196=back
197
198Which rules apply are determined as described in L<perlre/Which character set modifier is in effect?>.
8a118206 199
6b83a163
KW
200There are a number of security issues with the full Unicode list of word
201characters. See L<http://unicode.org/reports/tr36>.
202
203Also, for a somewhat finer-grained set of characters that are in programming
204language identifiers beyond the ASCII range, you may wish to instead use the
e2cfb18c
KW
205more customized L</Unicode Properties>, C<\p{ID_Start}>,
206C<\p{ID_Continue}>, C<\p{XID_Start}>, and C<\p{XID_Continue}>. See
207L<http://unicode.org/reports/tr31>.
6b83a163 208
b6538e4f 209Any character not matched by C<\w> is matched by C<\W>.
8a118206 210
ea449505
KW
211=head3 Whitespace
212
82206b5e
KW
213C<\s> matches any single character considered whitespace.
214
215=over
216
217=item If the C</a> modifier is in effect ...
218
d28d8023
KW
219In all Perl versions, C<\s> matches the 5 characters [\t\n\f\r ]; that
220is, the horizontal tab,
221the newline, the form feed, the carriage return, and the space.
779cf272 222Starting in Perl v5.18, it also matches the vertical tab, C<\cK>.
d28d8023 223See note C<[1]> below for a discussion of this.
82206b5e
KW
224
225=item otherwise ...
226
227=over
228
229=item For code points above 255 ...
230
231C<\s> matches exactly the code points above 255 shown with an "s" column
232in the table below.
233
234=item For code points below 256 ...
235
236=over
237
238=item if locale rules are in effect ...
239
d28d8023 240C<\s> matches whatever the locale considers to be whitespace.
82206b5e 241
04c2d19c 242=item if, instead, Unicode rules are in effect ...
82206b5e
KW
243
244C<\s> matches exactly the characters shown with an "s" column in the
245table below.
246
247=item otherwise ...
248
779cf272 249C<\s> matches [\t\n\f\r ] and, starting in Perl
d28d8023
KW
250v5.18, the vertical tab, C<\cK>.
251(See note C<[1]> below for a discussion of this.)
82206b5e
KW
252Note that this list doesn't include the non-breaking space.
253
254=back
255
256=back
257
258=back
259
260Which rules apply are determined as described in L<perlre/Which character set modifier is in effect?>.
8a118206 261
b6538e4f 262Any character not matched by C<\s> is matched by C<\S>.
8a118206 263
b6538e4f 264C<\h> matches any character considered horizontal whitespace;
8129baca 265this includes the platform's space and tab characters and several others
b6538e4f 266listed in the table below. C<\H> matches any character
8129baca
KW
267not considered horizontal whitespace. They use the platform's native
268character set, and do not consider any locale that may otherwise be in
269use.
ea449505 270
b6538e4f 271C<\v> matches any character considered vertical whitespace;
8129baca 272this includes the platform's carriage return and line feed characters (newline)
b6538e4f
TC
273plus several other characters, all listed in the table below.
274C<\V> matches any character not considered vertical whitespace.
8129baca
KW
275They use the platform's native character set, and do not consider any
276locale that may otherwise be in use.
8a118206
RGS
277
278C<\R> matches anything that can be considered a newline under Unicode
412a49a2
KW
279rules. It can match a multi-character sequence. It cannot be used inside
280a bracketed character class; use C<\v> instead (vertical whitespace).
281It uses the platform's
8129baca
KW
282native character set, and does not consider any locale that may
283otherwise be in use.
ea449505 284Details are discussed in L<perlrebackslash>.
8a118206 285
82206b5e 286Note that unlike C<\s> (and C<\d> and C<\w>), C<\h> and C<\v> always match
8129baca
KW
287the same characters, without regard to other factors, such as the active
288locale or whether the source string is in UTF-8 format.
8a118206 289
d28d8023
KW
290One might think that C<\s> is equivalent to C<[\h\v]>. This is indeed true
291starting in Perl v5.18, but prior to that, the sole difference was that the
292vertical tab (C<"\cK">) was not matched by C<\s>.
8a118206
RGS
293
294The following table is a complete listing of characters matched by
a9c9e371 295C<\s>, C<\h> and C<\v> as of Unicode 6.3.
8a118206 296
582da942 297The first column gives the Unicode code point of the character (in hex format),
8a118206 298the second column gives the (Unicode) name. The third column indicates
4b9734bf
KW
299by which class(es) the character is matched (assuming no locale is in
300effect that changes the C<\s> matching).
8a118206 301
fc28d2a3
KW
302 0x0009 CHARACTER TABULATION h s
303 0x000a LINE FEED (LF) vs
d28d8023 304 0x000b LINE TABULATION vs [1]
fc28d2a3
KW
305 0x000c FORM FEED (FF) vs
306 0x000d CARRIAGE RETURN (CR) vs
307 0x0020 SPACE h s
d28d8023
KW
308 0x0085 NEXT LINE (NEL) vs [2]
309 0x00a0 NO-BREAK SPACE h s [2]
fc28d2a3 310 0x1680 OGHAM SPACE MARK h s
fc28d2a3
KW
311 0x2000 EN QUAD h s
312 0x2001 EM QUAD h s
313 0x2002 EN SPACE h s
314 0x2003 EM SPACE h s
315 0x2004 THREE-PER-EM SPACE h s
316 0x2005 FOUR-PER-EM SPACE h s
317 0x2006 SIX-PER-EM SPACE h s
318 0x2007 FIGURE SPACE h s
319 0x2008 PUNCTUATION SPACE h s
320 0x2009 THIN SPACE h s
321 0x200a HAIR SPACE h s
322 0x2028 LINE SEPARATOR vs
323 0x2029 PARAGRAPH SEPARATOR vs
324 0x202f NARROW NO-BREAK SPACE h s
325 0x205f MEDIUM MATHEMATICAL SPACE h s
326 0x3000 IDEOGRAPHIC SPACE h s
8a118206
RGS
327
328=over 4
329
330=item [1]
331
779cf272
KW
332Prior to Perl v5.18, C<\s> did not match the vertical tab.
333C<[^\S\cK]> (obscurely) matches what C<\s> traditionally did.
d28d8023
KW
334
335=item [2]
336
82206b5e
KW
337NEXT LINE and NO-BREAK SPACE may or may not match C<\s> depending
338on the rules in effect. See
339L<the beginning of this section|/Whitespace>.
8a118206
RGS
340
341=back
342
8a118206
RGS
343=head3 Unicode Properties
344
c1c4ae3a
KW
345C<\pP> and C<\p{Prop}> are character classes to match characters that fit given
346Unicode properties. One letter property names can be used in the C<\pP> form,
347with the property name following the C<\p>, otherwise, braces are required.
348When using braces, there is a single form, which is just the property name
349enclosed in the braces, and a compound form which looks like C<\p{name=value}>,
b6538e4f 350which means to match if the property "name" for the character has that particular
c1c4ae3a 351"value".
e1b711da
KW
352For instance, a match for a number can be written as C</\pN/> or as
353C</\p{Number}/>, or as C</\p{Number=True}/>.
354Lowercase letters are matched by the property I<Lowercase_Letter> which
e2cfb18c 355has the short form I<Ll>. They need the braces, so are written as C</\p{Ll}/> or
e1b711da
KW
356C</\p{Lowercase_Letter}/>, or C</\p{General_Category=Lowercase_Letter}/>
357(the underscores are optional).
358C</\pLl/> is valid, but means something different.
8a118206
RGS
359It matches a two character string: a letter (Unicode property C<\pL>),
360followed by a lowercase C<l>.
361
67d5c462
KW
362What a Unicode property matches is never subject to locale rules, and
363if locale rules are not otherwise in effect, the use of a Unicode
364property will force the regular expression into using Unicode rules, if
365it isn't already.
82206b5e 366
56ca34ca
KW
367Note that almost all properties are immune to case-insensitive matching.
368That is, adding a C</i> regular expression modifier does not change what
82206b5e 369they match. There are two sets that are affected. The first set is
56ca34ca
KW
370C<Uppercase_Letter>,
371C<Lowercase_Letter>,
372and C<Titlecase_Letter>,
373all of which match C<Cased_Letter> under C</i> matching.
b6538e4f 374The second set is
56ca34ca
KW
375C<Uppercase>,
376C<Lowercase>,
377and C<Titlecase>,
378all of which match C<Cased> under C</i> matching.
379(The difference between these sets is that some things, such as Roman
e2cfb18c 380numerals, come in both upper and lower case, so they are C<Cased>, but
b6538e4f 381aren't considered to be letters, so they aren't C<Cased_Letter>s. They're
82206b5e
KW
382actually C<Letter_Number>s.)
383This set also includes its subsets C<PosixUpper> and C<PosixLower>, both
e2cfb18c 384of which under C</i> match C<PosixAlpha>.
56ca34ca
KW
385
386For more details on Unicode properties, see L<perlunicode/Unicode
387Character Properties>; for a
e1b711da 388complete list of possible properties, see
56ca34ca
KW
389L<perluniprops/Properties accessible through \p{} and \P{}>,
390which notes all forms that have C</i> differences.
e1b711da 391It is also possible to define your own properties. This is discussed in
8a118206
RGS
392L<perlunicode/User-Defined Character Properties>.
393
94b42e47 394Unicode properties are defined (surprise!) only on Unicode code points.
2d88a86a
KW
395Starting in v5.20, when matching against C<\p> and C<\P>, Perl treats
396non-Unicode code points (those above the legal Unicode maximum of
3970x10FFFF) as if they were typical unassigned Unicode code points.
94b42e47 398
2d88a86a
KW
399Prior to v5.20, Perl raised a warning and made all matches fail on
400non-Unicode code points. This could be somewhat surprising:
94b42e47 401
2d88a86a
KW
402 chr(0x110000) =~ \p{ASCII_Hex_Digit=True} # Fails on Perls < v5.20.
403 chr(0x110000) =~ \p{ASCII_Hex_Digit=False} # Also fails on Perls
404 # < v5.20
405
406Even though these two matches might be thought of as complements, until
407v5.20 they were so only on Unicode code points.
94b42e47 408
1532347b
KW
409Starting in perl v5.30, wildcards are allowed in Unicode property
410values. See L<perlunicode/Wildcards in Property Values>.
411
8a118206
RGS
412=head4 Examples
413
414 "a" =~ /\w/ # Match, "a" is a 'word' character.
415 "7" =~ /\w/ # Match, "7" is a 'word' character as well.
416 "a" =~ /\d/ # No match, "a" isn't a digit.
417 "7" =~ /\d/ # Match, "7" is a digit.
ea449505 418 " " =~ /\s/ # Match, a space is whitespace.
8a118206
RGS
419 "a" =~ /\D/ # Match, "a" is a non-digit.
420 "7" =~ /\D/ # No match, "7" is not a non-digit.
ea449505 421 " " =~ /\S/ # No match, a space is not non-whitespace.
8a118206 422
ea449505
KW
423 " " =~ /\h/ # Match, space is horizontal whitespace.
424 " " =~ /\v/ # No match, space is not vertical whitespace.
425 "\r" =~ /\v/ # Match, a return is vertical whitespace.
8a118206
RGS
426
427 "a" =~ /\pL/ # Match, "a" is a letter.
428 "a" =~ /\p{Lu}/ # No match, /\p{Lu}/ matches upper case letters.
429
430 "\x{0e0b}" =~ /\p{Thai}/ # Match, \x{0e0b} is the character
431 # 'THAI CHARACTER SO SO', and that's in
432 # Thai Unicode class.
ea449505 433 "a" =~ /\P{Lao}/ # Match, as "a" is not a Laotian character.
8a118206 434
82206b5e
KW
435It is worth emphasizing that C<\d>, C<\w>, etc, match single characters, not
436complete numbers or words. To match a number (that consists of digits),
437use C<\d+>; to match a word, use C<\w+>. But be aware of the security
438considerations in doing so, as mentioned above.
8a118206
RGS
439
440=head2 Bracketed Character Classes
441
442The third form of character class you can use in Perl regular expressions
6b83a163 443is the bracketed character class. In its simplest form, it lists the characters
c1c4ae3a 444that may be matched, surrounded by square brackets, like this: C<[aeiou]>.
ea449505 445This matches one of C<a>, C<e>, C<i>, C<o> or C<u>. Like the other
1f59b283 446character classes, exactly one character is matched.* To match
ea449505 447a longer string consisting of characters mentioned in the character
6b83a163 448class, follow the character class with a L<quantifier|perlre/Quantifiers>. For
b6538e4f 449instance, C<[aeiou]+> matches one or more lowercase English vowels.
8a118206
RGS
450
451Repeating a character in a character class has no
452effect; it's considered to be in the set only once.
453
454Examples:
455
456 "e" =~ /[aeiou]/ # Match, as "e" is listed in the class.
457 "p" =~ /[aeiou]/ # No match, "p" is not listed in the class.
458 "ae" =~ /^[aeiou]$/ # No match, a character class only matches
459 # a single character.
460 "ae" =~ /^[aeiou]+$/ # Match, due to the quantifier.
461
1f59b283
KW
462 -------
463
8f0cd35a
KW
464* There are two exceptions to a bracketed character class matching a
465single character only. Each requires special handling by Perl to make
466things work:
467
468=over
469
470=item *
471
472When the class is to match caselessly under C</i> matching rules, and a
473character that is explicitly mentioned inside the class matches a
1f59b283 474multiple-character sequence caselessly under Unicode rules, the class
8f0cd35a
KW
475will also match that sequence. For example, Unicode says that the
476letter C<LATIN SMALL LETTER SHARP S> should match the sequence C<ss>
477under C</i> rules. Thus,
1f59b283
KW
478
479 'ss' =~ /\A\N{LATIN SMALL LETTER SHARP S}\z/i # Matches
480 'ss' =~ /\A[aeioust\N{LATIN SMALL LETTER SHARP S}]\z/i # Matches
481
8f0cd35a
KW
482For this to happen, the class must not be inverted (see L</Negation>)
483and the character must be explicitly specified, and not be part of a
484multi-character range (not even as one of its endpoints). (L</Character
485Ranges> will be explained shortly.) Therefore,
9d53c457 486
eb9e3b14
KW
487 'ss' =~ /\A[\0-\x{ff}]\z/ui # Doesn't match
488 'ss' =~ /\A[\0-\N{LATIN SMALL LETTER SHARP S}]\z/ui # No match
489 'ss' =~ /\A[\xDF-\xDF]\z/ui # Matches on ASCII platforms, since
a845303d 490 # \xDF is LATIN SMALL LETTER SHARP S,
8f0cd35a
KW
491 # and the range is just a single
492 # element
9d53c457
KW
493
494Note that it isn't a good idea to specify these types of ranges anyway.
495
8f0cd35a
KW
496=item *
497
498Some names known to C<\N{...}> refer to a sequence of multiple characters,
499instead of the usual single character. When one of these is included in
500the class, the entire sequence is matched. For example,
501
502 "\N{TAMIL LETTER KA}\N{TAMIL VOWEL SIGN AU}"
503 =~ / ^ [\N{TAMIL SYLLABLE KAU}] $ /x;
504
505matches, because C<\N{TAMIL SYLLABLE KAU}> is a named sequence
506consisting of the two characters matched against. Like the other
eb9e3b14 507instance where a bracketed class can match multiple characters, and for
8f0cd35a
KW
508similar reasons, the class must not be inverted, and the named sequence
509may not appear in a range, even one where it is both endpoints. If
4a88d526
KW
510these happen, it is a fatal error if the character class is within the
511scope of L<C<use re 'strict>|re/'strict' mode>, or within an extended
512L<C<(?[...])>|/Extended Bracketed Character Classes> class; otherwise
513only the first code point is used (with a C<regexp>-type warning
514raised).
8f0cd35a
KW
515
516=back
517
8a118206
RGS
518=head3 Special Characters Inside a Bracketed Character Class
519
520Most characters that are meta characters in regular expressions (that
df225385 521is, characters that carry a special meaning like C<.>, C<*>, or C<(>) lose
8a118206
RGS
522their special meaning and can be used inside a character class without
523the need to escape them. For instance, C<[()]> matches either an opening
524parenthesis, or a closing parenthesis, and the parens inside the character
6e16fd37
KW
525class don't group or capture. Be aware that, unless the pattern is
526evaluated in single-quotish context, variable interpolation will take
527place before the bracketed class is parsed:
528
529 $, = "\t| ";
530 $a =~ m'[$,]'; # single-quotish: matches '$' or ','
531 $a =~ q{[$,]}' # same
532 $a =~ m/[$,]/; # double-quotish: matches "\t", "|", or " "
8a118206
RGS
533
534Characters that may carry a special meaning inside a character class are:
535C<\>, C<^>, C<->, C<[> and C<]>, and are discussed below. They can be
536escaped with a backslash, although this is sometimes not needed, in which
537case the backslash may be omitted.
538
539The sequence C<\b> is special inside a bracketed character class. While
6b83a163 540outside the character class, C<\b> is an assertion indicating a point
8a118206
RGS
541that does not have either two word characters or two non-word characters
542on either side, inside a bracketed character class, C<\b> matches a
543backspace character.
544
df225385
KW
545The sequences
546C<\a>,
547C<\c>,
548C<\e>,
549C<\f>,
550C<\n>,
e526e8bb 551C<\N{I<NAME>}>,
765fa144 552C<\N{U+I<hex char>}>,
df225385
KW
553C<\r>,
554C<\t>,
555and
556C<\x>
06ee63cd 557are also special and have the same meanings as they do outside a
eb9e3b14 558bracketed character class.
df225385 559
ea449505
KW
560Also, a backslash followed by two or three octal digits is considered an octal
561number.
df225385 562
6b83a163
KW
563A C<[> is not special inside a character class, unless it's the start of a
564POSIX character class (see L</POSIX Character Classes> below). It normally does
565not need escaping.
8a118206 566
6b83a163
KW
567A C<]> is normally either the end of a POSIX character class (see
568L</POSIX Character Classes> below), or it signals the end of the bracketed
569character class. If you want to include a C<]> in the set of characters, you
570must generally escape it.
b6538e4f 571
8a118206
RGS
572However, if the C<]> is the I<first> (or the second if the first
573character is a caret) character of a bracketed character class, it
574does not denote the end of the class (as you cannot have an empty class)
575and is considered part of the set of characters that can be matched without
576escaping.
577
578Examples:
579
580 "+" =~ /[+?*]/ # Match, "+" in a character class is not special.
090752cc 581 "\cH" =~ /[\b]/ # Match, \b inside in a character class
c1c4ae3a 582 # is equivalent to a backspace.
090752cc 583 "]" =~ /[][]/ # Match, as the character class contains
8a118206
RGS
584 # both [ and ].
585 "[]" =~ /[[]]/ # Match, the pattern contains a character class
52f4d632 586 # containing just [, and the character class is
8a118206
RGS
587 # followed by a ].
588
77c8f263
KW
589=head3 Bracketed Character Classes and the C</xx> pattern modifier
590
591Normally SPACE and TAB characters have no special meaning inside a
592bracketed character class; they are just added to the list of characters
593matched by the class. But if the L<C</xx>|perlre/E<sol>x and E<sol>xx>
594pattern modifier is in effect, they are generally ignored and can be
595added to improve readability. They can't be added in the middle of a
596single construct:
597
598 / [ \x{10 FFFF} ] /xx # WRONG!
599
600The SPACE in the middle of the hex constant is illegal.
601
602To specify a literal SPACE character, you can escape it with a
603backslash, like:
604
605 /[ a e i o u \ ]/xx
606
607This matches the English vowels plus the SPACE character.
608
609For clarity, you should already have been using C<\t> to specify a
610literal tab, and C<\t> is unaffected by C</xx>.
611
8a118206
RGS
612=head3 Character Ranges
613
614It is not uncommon to want to match a range of characters. Luckily, instead
b6538e4f 615of listing all characters in the range, one may use the hyphen (C<->).
8a118206 616If inside a bracketed character class you have two characters separated
b6538e4f 617by a hyphen, it's treated as if all characters between the two were in
8a118206 618the class. For instance, C<[0-9]> matches any ASCII digit, and C<[a-m]>
e2cfb18c 619matches any lowercase letter from the first half of the ASCII alphabet.
8a118206
RGS
620
621Note that the two characters on either side of the hyphen are not
765fa144 622necessarily both letters or both digits. Any character is possible,
8a118206 623although not advisable. C<['-?]> contains a range of characters, but
b6538e4f 624most people will not know which characters that means. Furthermore,
8a118206
RGS
625such ranges may lead to portability problems if the code has to run on
626a platform that uses a different character set, such as EBCDIC.
627
ea449505
KW
628If a hyphen in a character class cannot syntactically be part of a range, for
629instance because it is the first or the last character of the character class,
b6538e4f
TC
630or if it immediately follows a range, the hyphen isn't special, and so is
631considered a character to be matched literally. If you want a hyphen in
632your set of characters to be matched and its position in the class is such
633that it could be considered part of a range, you must escape that hyphen
634with a backslash.
8a118206
RGS
635
636Examples:
637
638 [a-z] # Matches a character that is a lower case ASCII letter.
c1c4ae3a
KW
639 [a-fz] # Matches any letter between 'a' and 'f' (inclusive) or
640 # the letter 'z'.
8a118206
RGS
641 [-z] # Matches either a hyphen ('-') or the letter 'z'.
642 [a-f-m] # Matches any letter between 'a' and 'f' (inclusive), the
643 # hyphen ('-'), or the letter 'm'.
644 ['-?] # Matches any of the characters '()*+,-./0123456789:;<=>?
645 # (But not on an EBCDIC platform).
c7d25594
KW
646 [\N{APOSTROPHE}-\N{QUESTION MARK}]
647 # Matches any of the characters '()*+,-./0123456789:;<=>?
648 # even on an EBCDIC platform.
ad63362f 649 [\N{U+27}-\N{U+3F}] # Same. (U+27 is "'", and U+3F is "?")
c7d25594 650
dabde021 651As the final two examples above show, you can achieve portability to
c7d25594
KW
652non-ASCII platforms by using the C<\N{...}> form for the range
653endpoints. These indicate that the specified range is to be interpreted
654using Unicode values, so C<[\N{U+27}-\N{U+3F}]> means to match
655C<\N{U+27}>, C<\N{U+28}>, C<\N{U+29}>, ..., C<\N{U+3D}>, C<\N{U+3E}>,
656and C<\N{U+3F}>, whatever the native code point versions for those are.
b927b7e9
KW
657These are called "Unicode" ranges. If either end is of the C<\N{...}>
658form, the range is considered Unicode. A C<regexp> warning is raised
659under C<S<"use re 'strict'">> if the other endpoint is specified
660non-portably:
661
662 [\N{U+00}-\x09] # Warning under re 'strict'; \x09 is non-portable
663 [\N{U+00}-\t] # No warning;
664
665Both of the above match the characters C<\N{U+00}> C<\N{U+01}>, ...
666C<\N{U+08}>, C<\N{U+09}>, but the C<\x09> looks like it could be a
667mistake so the warning is raised (under C<re 'strict'>) for it.
c7d25594
KW
668
669Perl also guarantees that the ranges C<A-Z>, C<a-z>, C<0-9>, and any
09e43397 670subranges of these match what an English-only speaker would expect them
c7d25594
KW
671to match on any platform. That is, C<[A-Z]> matches the 26 ASCII
672uppercase letters;
09e43397
KW
673C<[a-z]> matches the 26 lowercase letters; and C<[0-9]> matches the 10
674digits. Subranges, like C<[h-k]>, match correspondingly, in this case
675just the four letters C<"h">, C<"i">, C<"j">, and C<"k">. This is the
676natural behavior on ASCII platforms where the code points (ordinal
677values) for C<"h"> through C<"k"> are consecutive integers (0x68 through
6780x6B). But special handling to achieve this may be needed on platforms
679with a non-ASCII native character set. For example, on EBCDIC
680platforms, the code point for C<"h"> is 0x88, C<"i"> is 0x89, C<"j"> is
6810x91, and C<"k"> is 0x92. Perl specially treats C<[h-k]> to exclude the
682seven code points in the gap: 0x8A through 0x90. This special handling is
683only invoked when the range is a subrange of one of the ASCII uppercase,
684lowercase, and digit ranges, AND each end of the range is expressed
685either as a literal, like C<"A">, or as a named character (C<\N{...}>,
686including the C<\N{U+...> form).
687
688EBCDIC Examples:
689
690 [i-j] # Matches either "i" or "j"
691 [i-\N{LATIN SMALL LETTER J}] # Same
692 [i-\N{U+6A}] # Same
693 [\N{U+69}-\N{U+6A}] # Same
694 [\x{89}-\x{91}] # Matches 0x89 ("i"), 0x8A .. 0x90, 0x91 ("j")
695 [i-\x{91}] # Same
696 [\x{89}-j] # Same
697 [i-J] # Matches, 0x89 ("i") .. 0xC1 ("J"); special
698 # handling doesn't apply because range is mixed
699 # case
8a118206
RGS
700
701=head3 Negation
702
703It is also possible to instead list the characters you do not want to
704match. You can do so by using a caret (C<^>) as the first character in the
b6538e4f 705character class. For instance, C<[^a-z]> matches any character that is not a
e2cfb18c
KW
706lowercase ASCII letter, which therefore includes more than a million
707Unicode code points. The class is said to be "negated" or "inverted".
8a118206
RGS
708
709This syntax make the caret a special character inside a bracketed character
710class, but only if it is the first character of the class. So if you want
82206b5e 711the caret as one of the characters to match, either escape the caret or
e2cfb18c 712else don't list it first.
8a118206 713
1f59b283 714In inverted bracketed character classes, Perl ignores the Unicode rules
8f0cd35a
KW
715that normally say that named sequence, and certain characters should
716match a sequence of multiple characters use under caseless C</i>
717matching. Following those rules could lead to highly confusing
718situations:
1f59b283 719
582da942 720 "ss" =~ /^[^\xDF]+$/ui; # Matches!
1f59b283
KW
721
722This should match any sequences of characters that aren't C<\xDF> nor
723what C<\xDF> matches under C</i>. C<"s"> isn't C<\xDF>, but Unicode
724says that C<"ss"> is what C<\xDF> matches under C</i>. So which one
725"wins"? Do you fail the match because the string has C<ss> or accept it
582da942 726because it has an C<s> followed by another C<s>? Perl has chosen the
8f0cd35a 727latter. (See note in L</Bracketed Character Classes> above.)
1f59b283 728
8a118206
RGS
729Examples:
730
731 "e" =~ /[^aeiou]/ # No match, the 'e' is listed.
732 "x" =~ /[^aeiou]/ # Match, as 'x' isn't a lowercase vowel.
733 "^" =~ /[^^]/ # No match, matches anything that isn't a caret.
734 "^" =~ /[x^]/ # Match, caret is not special here.
735
736=head3 Backslash Sequences
737
ea449505 738You can put any backslash sequence character class (with the exception of
765fa144 739C<\N> and C<\R>) inside a bracketed character class, and it will act just
b6538e4f
TC
740as if you had put all characters matched by the backslash sequence inside the
741character class. For instance, C<[a-f\d]> matches any decimal digit, or any
6b83a163
KW
742of the lowercase letters between 'a' and 'f' inclusive.
743
744C<\N> within a bracketed character class must be of the forms C<\N{I<name>}>
765fa144 745or C<\N{U+I<hex char>}>, and NOT be the form that matches non-newlines,
6b83a163
KW
746for the same reason that a dot C<.> inside a bracketed character class loses
747its special meaning: it matches nearly anything, which generally isn't what you
748want to happen.
df225385 749
8a118206
RGS
750
751Examples:
752
753 /[\p{Thai}\d]/ # Matches a character that is either a Thai
754 # character, or a digit.
755 /[^\p{Arabic}()]/ # Matches a character that is neither an Arabic
756 # character, nor a parenthesis.
757
758Backslash sequence character classes cannot form one of the endpoints
6b83a163
KW
759of a range. Thus, you can't say:
760
761 /[\p{Thai}-\d]/ # Wrong!
8a118206 762
6b83a163 763=head3 POSIX Character Classes
ea449505 764X<character class> X<\p> X<\p{}>
ea449505
KW
765X<alpha> X<alnum> X<ascii> X<blank> X<cntrl> X<digit> X<graph>
766X<lower> X<print> X<punct> X<space> X<upper> X<word> X<xdigit>
8a118206 767
d66e1f56 768POSIX character classes have the form C<[:class:]>, where I<class> is the
6b83a163 769name, and the C<[:> and C<:]> delimiters. POSIX character classes only appear
8a118206 770I<inside> bracketed character classes, and are a convenient and descriptive
82206b5e 771way of listing a group of characters.
6b83a163
KW
772
773Be careful about the syntax,
8a118206
RGS
774
775 # Correct:
776 $string =~ /[[:alpha:]]/
777
778 # Incorrect (will warn):
779 $string =~ /[:alpha:]/
780
781The latter pattern would be a character class consisting of a colon,
782and the letters C<a>, C<l>, C<p> and C<h>.
d66e1f56 783
82206b5e 784POSIX character classes can be part of a larger bracketed character class.
b6538e4f 785For example,
ea449505
KW
786
787 [01[:alpha:]%]
788
789is valid and matches '0', '1', any alphabetic character, and the percent sign.
8a118206
RGS
790
791Perl recognizes the following POSIX character classes:
792
8a0ab3a4
KW
793 alpha Any alphabetical character (e.g., [A-Za-z]).
794 alnum Any alphanumeric character (e.g., [A-Za-z0-9]).
ea449505 795 ascii Any character in the ASCII character set.
ea8b8ad2 796 blank A GNU extension, equal to a space or a horizontal tab ("\t").
ea449505 797 cntrl Any control character. See Note [2] below.
8a0ab3a4 798 digit Any decimal digit (e.g., [0-9]), equivalent to "\d".
ea449505 799 graph Any printable character, excluding a space. See Note [3] below.
8a0ab3a4 800 lower Any lowercase character (e.g., [a-z]).
ea449505 801 print Any printable character, including a space. See Note [4] below.
c1c4ae3a 802 punct Any graphical character excluding "word" characters. Note [5].
d28d8023
KW
803 space Any whitespace character. "\s" including the vertical tab
804 ("\cK").
8a0ab3a4
KW
805 upper Any uppercase character (e.g., [A-Z]).
806 word A Perl extension (e.g., [A-Za-z0-9_]), equivalent to "\w".
7835a09a 807 xdigit Any hexadecimal digit (e.g., [0-9a-fA-F]). Note [7].
ea449505 808
93106464
KW
809Like the L<Unicode properties|/Unicode Properties>, most of the POSIX
810properties match the same regardless of whether case-insensitive (C</i>)
811matching is in effect or not. The two exceptions are C<[:upper:]> and
812C<[:lower:]>. Under C</i>, they each match the union of C<[:upper:]> and
813C<[:lower:]>.
814
ea449505
KW
815Most POSIX character classes have two Unicode-style C<\p> property
816counterparts. (They are not official Unicode properties, but Perl extensions
817derived from official Unicode properties.) The table below shows the relation
818between POSIX character classes and these counterparts.
819
820One counterpart, in the column labelled "ASCII-range Unicode" in
b6538e4f 821the table, matches only characters in the ASCII character set.
ea449505
KW
822
823The other counterpart, in the column labelled "Full-range Unicode", matches any
824appropriate characters in the full Unicode character set. For example,
b6538e4f 825C<\p{Alpha}> matches not just the ASCII alphabetic characters, but any
82206b5e 826character in the entire Unicode character set considered alphabetic.
582da942 827An entry in the column labelled "backslash sequence" is a (short)
5db9882c 828equivalent.
ea449505 829
cbc24f92
KW
830 [[:...:]] ASCII-range Full-range backslash Note
831 Unicode Unicode sequence
ea449505 832 -----------------------------------------------------
cbc24f92
KW
833 alpha \p{PosixAlpha} \p{XPosixAlpha}
834 alnum \p{PosixAlnum} \p{XPosixAlnum}
82206b5e 835 ascii \p{ASCII}
cbc24f92
KW
836 blank \p{PosixBlank} \p{XPosixBlank} \h [1]
837 or \p{HorizSpace} [1]
838 cntrl \p{PosixCntrl} \p{XPosixCntrl} [2]
839 digit \p{PosixDigit} \p{XPosixDigit} \d
840 graph \p{PosixGraph} \p{XPosixGraph} [3]
841 lower \p{PosixLower} \p{XPosixLower}
842 print \p{PosixPrint} \p{XPosixPrint} [4]
843 punct \p{PosixPunct} \p{XPosixPunct} [5]
844 \p{PerlSpace} \p{XPerlSpace} \s [6]
845 space \p{PosixSpace} \p{XPosixSpace} [6]
846 upper \p{PosixUpper} \p{XPosixUpper}
847 word \p{PosixWord} \p{XPosixWord} \w
7835a09a 848 xdigit \p{PosixXDigit} \p{XPosixXDigit} [7]
8a118206
RGS
849
850=over 4
851
ea449505
KW
852=item [1]
853
854C<\p{Blank}> and C<\p{HorizSpace}> are synonyms.
855
856=item [2]
8a118206 857
ea449505 858Control characters don't produce output as such, but instead usually control
b6538e4f 859the terminal somehow: for example, newline and backspace are control characters.
93106464
KW
860On ASCII platforms, in the ASCII range, characters whose code points are
861between 0 and 31 inclusive, plus 127 (C<DEL>) are control characters; on
862EBCDIC platforms, their counterparts are control characters.
8a118206 863
ea449505 864=item [3]
8a118206
RGS
865
866Any character that is I<graphical>, that is, visible. This class consists
b6538e4f 867of all alphanumeric characters and all punctuation characters.
8a118206 868
ea449505 869=item [4]
8a118206 870
b6538e4f
TC
871All printable characters, which is the set of all graphical characters
872plus those whitespace characters which are not also controls.
ea449505 873
b6dac59a 874=item [5]
ea449505 875
b6538e4f 876C<\p{PosixPunct}> and C<[[:punct:]]> in the ASCII range match all
ea449505
KW
877non-controls, non-alphanumeric, non-space characters:
878C<[-!"#$%&'()*+,./:;<=E<gt>?@[\\\]^_`{|}~]> (although if a locale is in effect,
879it could alter the behavior of C<[[:punct:]]>).
880
cbc24f92
KW
881The similarly named property, C<\p{Punct}>, matches a somewhat different
882set in the ASCII range, namely
0be9b861
KW
883C<[-!"#%&'()*,./:;?@[\\\]_{}]>. That is, it is missing the nine
884characters C<[$+E<lt>=E<gt>^`|~]>.
6c5a041f
KW
885This is because Unicode splits what POSIX considers to be punctuation into two
886categories, Punctuation and Symbols.
887
e2cfb18c 888C<\p{XPosixPunct}> and (under Unicode rules) C<[[:punct:]]>, match what
765fa144
KW
889C<\p{PosixPunct}> matches in the ASCII range, plus what C<\p{Punct}>
890matches. This is different than strictly matching according to
891C<\p{Punct}>. Another way to say it is that
82206b5e
KW
892if Unicode rules are in effect, C<[[:punct:]]> matches all characters
893that Unicode considers punctuation, plus all ASCII-range characters that
894Unicode considers symbols.
8a118206 895
ea449505 896=item [6]
8a118206 897
7fa2fdc0 898C<\p{XPerlSpace}> and C<\p{Space}> match identically starting with Perl
d28d8023 899v5.18. In earlier versions, these differ only in that in non-locale
779cf272 900matching, C<\p{XPerlSpace}> did not match the vertical tab, C<\cK>.
d28d8023 901Same for the two ASCII-only range forms.
8a118206 902
7835a09a
KW
903=item [7]
904
905Unlike C<[[:digit:]]> which matches digits in many writing systems, such
906as Thai and Devanagari, there are currently only two sets of hexadecimal
907digits, and it is unlikely that more will be added. This is because you
908not only need the ten digits, but also the six C<[A-F]> (and C<[a-f]>)
909to correspond. That means only the Latin script is suitable for these,
910and Unicode has only two sets of these, the familiar ASCII set, and the
911fullwidth forms starting at U+FF10 (FULLWIDTH DIGIT ZERO).
912
8a118206
RGS
913=back
914
ab6199be 915There are various other synonyms that can be used besides the names
4cb26c52 916listed in the table. For example, C<\p{XPosixAlpha}> can be written as
ab6199be 917C<\p{Alpha}>. All are listed in
d66e1f56 918L<perluniprops/Properties accessible through \p{} and \P{}>.
ab6199be
KW
919
920Both the C<\p> counterparts always assume Unicode rules are in effect.
921On ASCII platforms, this means they assume that the code points from 128
922to 255 are Latin-1, and that means that using them under locale rules is
923unwise unless the locale is guaranteed to be Latin-1 or UTF-8. In contrast, the
924POSIX character classes are useful under locale rules. They are
925affected by the actual rules in effect, as follows:
926
927=over
928
929=item If the C</a> modifier, is in effect ...
930
931Each of the POSIX classes matches exactly the same as their ASCII-range
932counterparts.
933
934=item otherwise ...
935
936=over
937
938=item For code points above 255 ...
939
940The POSIX class matches the same as its Full-range counterpart.
941
942=item For code points below 256 ...
943
944=over
945
946=item if locale rules are in effect ...
947
a145a423
KW
948The POSIX class matches according to the locale, except:
949
950=over
951
952=item C<word>
953
954also includes the platform's native underscore character, no matter what
8129baca 955the locale is.
ab6199be 956
a145a423
KW
957=item C<ascii>
958
959on platforms that don't have the POSIX C<ascii> extension, this matches
960just the platform's native ASCII-range characters.
961
962=item C<blank>
963
964on platforms that don't have the POSIX C<blank> extension, this matches
965just the platform's native tab and space characters.
966
967=back
968
04c2d19c 969=item if, instead, Unicode rules are in effect ...
ab6199be
KW
970
971The POSIX class matches the same as the Full-range counterpart.
972
973=item otherwise ...
974
975The POSIX class matches the same as the ASCII range counterpart.
976
977=back
978
979=back
980
981=back
982
983Which rules apply are determined as described in
984L<perlre/Which character set modifier is in effect?>.
985
1f59b283 986=head4 Negation of POSIX character classes
ea449505 987X<character class, negation>
8a118206
RGS
988
989A Perl extension to the POSIX character class is the ability to
990negate it. This is done by prefixing the class name with a caret (C<^>).
991Some examples:
992
ea449505
KW
993 POSIX ASCII-range Full-range backslash
994 Unicode Unicode sequence
995 -----------------------------------------------------
cbc24f92
KW
996 [[:^digit:]] \P{PosixDigit} \P{XPosixDigit} \D
997 [[:^space:]] \P{PosixSpace} \P{XPosixSpace}
998 \P{PerlSpace} \P{XPerlSpace} \S
999 [[:^word:]] \P{PerlWord} \P{XPosixWord} \W
1000
765fa144 1001The backslash sequence can mean either ASCII- or Full-range Unicode,
82206b5e 1002depending on various factors as described in L<perlre/Which character set modifier is in effect?>.
8a118206
RGS
1003
1004=head4 [= =] and [. .]
1005
b6538e4f 1006Perl recognizes the POSIX character classes C<[=class=]> and
82206b5e 1007C<[.class.]>, but does not (yet?) support them. Any attempt to use
b6538e4f 1008either construct raises an exception.
8a118206
RGS
1009
1010=head4 Examples
1011
1012 /[[:digit:]]/ # Matches a character that is a digit.
1013 /[01[:lower:]]/ # Matches a character that is either a
1014 # lowercase letter, or '0' or '1'.
c1c4ae3a 1015 /[[:digit:][:^xdigit:]]/ # Matches a character that can be anything
bc943be5
KW
1016 # except the letters 'a' to 'f' and 'A' to
1017 # 'F'. This is because the main character
1018 # class is composed of two POSIX character
1019 # classes that are ORed together, one that
1020 # matches any digit, and the other that
1021 # matches anything that isn't a hex digit.
1022 # The OR adds the digits, leaving only the
1023 # letters 'a' to 'f' and 'A' to 'F' excluded.
572224ce
KW
1024
1025=head3 Extended Bracketed Character Classes
1026X<character class>
1027X<set operations>
1028
1029This is a fancy bracketed character class that can be used for more
1030readable and less error-prone classes, and to perform set operations,
1031such as intersection. An example is
1032
1033 /(?[ \p{Thai} & \p{Digit} ])/
1034
1035This will match all the digit characters that are in the Thai script.
1036
1037This is an experimental feature available starting in 5.18, and is
1038subject to change as we gain field experience with it. Any attempt to
1039use it will raise a warning, unless disabled via
1040
1041 no warnings "experimental::regex_sets";
1042
1043Comments on this feature are welcome; send email to
1044C<perl5-porters@perl.org>.
1045
a60b7922
KW
1046The rules used by L<C<use re 'strict>|re/'strict' mode> apply to this
1047construct.
1048
572224ce
KW
1049We can extend the example above:
1050
1051 /(?[ ( \p{Thai} + \p{Lao} ) & \p{Digit} ])/
1052
1053This matches digits that are in either the Thai or Laotian scripts.
1054
1055Notice the white space in these examples. This construct always has
77c8f263 1056the C<E<sol>xx> modifier turned on within it.
572224ce
KW
1057
1058The available binary operators are:
1059
1060 & intersection
1061 + union
1062 | another name for '+', hence means union
1063 - subtraction (the result matches the set consisting of those
1064 code points matched by the first operand, excluding any that
1065 are also matched by the second operand)
1066 ^ symmetric difference (the union minus the intersection). This
1067 is like an exclusive or, in that the result is the set of code
1068 points that are matched by either, but not both, of the
1069 operands.
1070
1071There is one unary operator:
1072
1073 ! complement
1074
6798c95d
KW
1075All the binary operators left associate; C<"&"> is higher precedence
1076than the others, which all have equal precedence. The unary operator
1077right associates, and has highest precedence. Thus this follows the
1078normal Perl precedence rules for logical operators. Use parentheses to
1079override the default precedence and associativity.
572224ce
KW
1080
1081The main restriction is that everything is a metacharacter. Thus,
1082you cannot refer to single characters by doing something like this:
1083
1084 /(?[ a + b ])/ # Syntax error!
1085
1086The easiest way to specify an individual typable character is to enclose
1087it in brackets:
1088
1089 /(?[ [a] + [b] ])/
1090
1091(This is the same thing as C<[ab]>.) You could also have said the
1092equivalent:
1093
1094 /(?[[ a b ]])/
1095
de36fb2e
KW
1096(You can, of course, specify single characters by using, C<\x{...}>,
1097C<\N{...}>, etc.)
572224ce
KW
1098
1099This last example shows the use of this construct to specify an ordinary
1100bracketed character class without additional set operations. Note the
77c8f263
KW
1101white space within it. This is allowed because C<E<sol>xx> is
1102automatically turned on within this construct.
572224ce 1103
572224ce 1104All the other escapes accepted by normal bracketed character classes are
7d4c055d
KW
1105accepted here as well.
1106
1107Because this construct compiles under
1108L<C<use re 'strict>|re/'strict' mode>, unrecognized escapes that
1109generate warnings in normal classes are fatal errors here, as well as
1110all other warnings from these class elements, as well as some
1111practices that don't currently warn outside C<re 'strict'>. For example
1112you cannot say
572224ce
KW
1113
1114 /(?[ [ \xF ] ])/ # Syntax error!
1115
1116You have to have two hex digits after a braceless C<\x> (use a leading
1117zero to make two). These restrictions are to lower the incidence of
1118typos causing the class to not match what you thought it would.
1119
f194034a
KW
1120If a regular bracketed character class contains a C<\p{}> or C<\P{}> and
1121is matched against a non-Unicode code point, a warning may be
1122raised, as the result is not Unicode-defined. No such warning will come
1123when using this extended form.
1124
572224ce
KW
1125The final difference between regular bracketed character classes and
1126these, is that it is not possible to get these to match a
1127multi-character fold. Thus,
1128
1129 /(?[ [\xDF] ])/iu
1130
1131does not match the string C<ss>.
1132
1133You don't have to enclose POSIX class names inside double brackets,
1134hence both of the following work:
1135
1136 /(?[ [:word:] - [:lower:] ])/
1137 /(?[ [[:word:]] - [[:lower:]] ])/
1138
1139Any contained POSIX character classes, including things like C<\w> and C<\D>
1140respect the C<E<sol>a> (and C<E<sol>aa>) modifiers.
1141
19a498a4
YO
1142Note that C<< (?[ ]) >> is a regex-compile-time construct. Any attempt
1143to use something which isn't knowable at the time the containing regular
572224ce 1144expression is compiled is a fatal error. In practice, this means
11a9b3e0 1145just three limitations:
572224ce
KW
1146
1147=over 4
1148
1149=item 1
1150
a0bd1a30
KW
1151When compiled within the scope of C<use locale> (or the C<E<sol>l> regex
1152modifier), this construct assumes that the execution-time locale will be
1153a UTF-8 one, and the generated pattern always uses Unicode rules. What
1154gets matched or not thus isn't dependent on the actual runtime locale, so
1155tainting is not enabled. But a C<locale> category warning is raised
1156if the runtime locale turns out to not be UTF-8.
572224ce
KW
1157
1158=item 2
1159
1160Any
1161L<user-defined property|perlunicode/"User-Defined Character Properties">
1162used must be already defined by the time the regular expression is
1163compiled (but note that this construct can be used instead of such
1164properties).
1165
1166=item 3
1167
1168A regular expression that otherwise would compile
1169using C<E<sol>d> rules, and which uses this construct will instead
1170use C<E<sol>u>. Thus this construct tells Perl that you don't want
1171C<E<sol>d> rules for the entire regular expression containing it.
1172
1173=back
1174
572224ce
KW
1175Note that skipping white space applies only to the interior of this
1176construct. There must not be any space between any of the characters
1177that form the initial C<(?[>. Nor may there be space between the
1178closing C<])> characters.
1179
11a9b3e0 1180Just as in all regular expressions, the pattern can be built up by
572224ce 1181including variables that are interpolated at regex compilation time.
1c484ed4
KW
1182But its best to compile each sub-component.
1183
1184 my $thai_or_lao = qr/(?[ \p{Thai} + \p{Lao} ])/;
1185 my $lower = qr/(?[ \p{Lower} + \p{Digit} ])/;
1186
1187When these are embedded in another pattern, what they match does not
1188change, regardless of parenthesization or what modifiers are in effect
1189in that outer pattern. If you fail to compile the subcomponents, you
1190can get some nasty surprises. For example:
572224ce
KW
1191
1192 my $thai_or_lao = '\p{Thai} + \p{Lao}';
1193 ...
1194 qr/(?[ \p{Digit} & $thai_or_lao ])/;
1195
1196compiles to
1197
1198 qr/(?[ \p{Digit} & \p{Thai} + \p{Lao} ])/;
1199
1c484ed4
KW
1200But this does not have the effect that someone reading the source code
1201would likely expect, as the intersection applies just to C<\p{Thai}>,
1202excluding the Laotian. Its best to compile the subcomponents, but you
1203could also parenthesize the component pieces:
572224ce
KW
1204
1205 my $thai_or_lao = '( \p{Thai} + \p{Lao} )';
1206
1207But any modifiers will still apply to all the components:
1208
1209 my $lower = '\p{Lower} + \p{Digit}';
1210 qr/(?[ \p{Greek} & $lower ])/i;
1211
1c484ed4
KW
1212matches upper case things. So just, compile the subcomponents, as
1213illustrated above.
572224ce
KW
1214
1215Due to the way that Perl parses things, your parentheses and brackets
1216may need to be balanced, even including comments. If you run into any
1217examples, please send them to C<perlbug@perl.org>, so that we can have a
1218concrete example for this man page.
1219
1220We may change it so that things that remain legal uses in normal bracketed
1221character classes might become illegal within this experimental
1222construct. One proposal, for example, is to forbid adjacent uses of the
1223same character, as in C<(?[ [aa] ])>. The motivation for such a change
1224is that this usage is likely a typo, as the second "a" adds nothing.