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