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