1PERLREBACKSLASH(1) Perl Programmers Reference Guide PERLREBACKSLASH(1)
2
3
4
6 perlrebackslash - Perl Regular Expression Backslash Sequences and
7 Escapes
8
10 The top level documentation about Perl regular expressions is found in
11 perlre.
12
13 This document describes all backslash and escape sequences. After
14 explaining the role of the backslash, it lists all the sequences that
15 have a special meaning in Perl regular expressions (in alphabetical
16 order), then describes each of them.
17
18 Most sequences are described in detail in different documents; the
19 primary purpose of this document is to have a quick reference guide
20 describing all backslash and escape sequences.
21
22 The backslash
23 In a regular expression, the backslash can perform one of two tasks: it
24 either takes away the special meaning of the character following it
25 (for instance, "\|" matches a vertical bar, it's not an alternation),
26 or it is the start of a backslash or escape sequence.
27
28 The rules determining what it is are quite simple: if the character
29 following the backslash is an ASCII punctuation (non-word) character
30 (that is, anything that is not a letter, digit, or underscore), then
31 the backslash just takes away any special meaning of the character
32 following it.
33
34 If the character following the backslash is an ASCII letter or an ASCII
35 digit, then the sequence may be special; if so, it's listed below. A
36 few letters have not been used yet, so escaping them with a backslash
37 doesn't change them to be special. A future version of Perl may assign
38 a special meaning to them, so if you have warnings turned on, Perl
39 issues a warning if you use such a sequence. [1].
40
41 It is however guaranteed that backslash or escape sequences never have
42 a punctuation character following the backslash, not now, and not in a
43 future version of Perl 5. So it is safe to put a backslash in front of
44 a non-word character.
45
46 Note that the backslash itself is special; if you want to match a
47 backslash, you have to escape the backslash with a backslash: "/\\/"
48 matches a single backslash.
49
50 [1] There is one exception. If you use an alphanumeric character as the
51 delimiter of your pattern (which you probably shouldn't do for
52 readability reasons), you have to escape the delimiter if you want
53 to match it. Perl won't warn then. See also "Gory details of
54 parsing quoted constructs" in perlop.
55
56 All the sequences and escapes
57 Those not usable within a bracketed character class (like "[\da-z]")
58 are marked as "Not in []."
59
60 \000 Octal escape sequence. See also \o{}.
61 \1 Absolute backreference. Not in [].
62 \a Alarm or bell.
63 \A Beginning of string. Not in [].
64 \b{}, \b Boundary. (\b is a backspace in []).
65 \B{}, \B Not a boundary. Not in [].
66 \cX Control-X.
67 \d Match any digit character.
68 \D Match any character that isn't a digit.
69 \e Escape character.
70 \E Turn off \Q, \L and \U processing. Not in [].
71 \f Form feed.
72 \F Foldcase till \E. Not in [].
73 \g{}, \g1 Named, absolute or relative backreference.
74 Not in [].
75 \G Pos assertion. Not in [].
76 \h Match any horizontal whitespace character.
77 \H Match any character that isn't horizontal whitespace.
78 \k{}, \k<>, \k'' Named backreference. Not in [].
79 \K Keep the stuff left of \K. Not in [].
80 \l Lowercase next character. Not in [].
81 \L Lowercase till \E. Not in [].
82 \n (Logical) newline character.
83 \N Match any character but newline. Not in [].
84 \N{} Named or numbered (Unicode) character or sequence.
85 \o{} Octal escape sequence.
86 \p{}, \pP Match any character with the given Unicode property.
87 \P{}, \PP Match any character without the given property.
88 \Q Quote (disable) pattern metacharacters till \E. Not
89 in [].
90 \r Return character.
91 \R Generic new line. Not in [].
92 \s Match any whitespace character.
93 \S Match any character that isn't a whitespace.
94 \t Tab character.
95 \u Titlecase next character. Not in [].
96 \U Uppercase till \E. Not in [].
97 \v Match any vertical whitespace character.
98 \V Match any character that isn't vertical whitespace
99 \w Match any word character.
100 \W Match any character that isn't a word character.
101 \x{}, \x00 Hexadecimal escape sequence.
102 \X Unicode "extended grapheme cluster". Not in [].
103 \z End of string. Not in [].
104 \Z End of string. Not in [].
105
106 Character Escapes
107 Fixed characters
108
109 A handful of characters have a dedicated character escape. The
110 following table shows them, along with their ASCII code points (in
111 decimal and hex), their ASCII name, the control escape on ASCII
112 platforms and a short description. (For EBCDIC platforms, see
113 "OPERATOR DIFFERENCES" in perlebcdic.)
114
115 Seq. Code Point ASCII Cntrl Description.
116 Dec Hex
117 \a 7 07 BEL \cG alarm or bell
118 \b 8 08 BS \cH backspace [1]
119 \e 27 1B ESC \c[ escape character
120 \f 12 0C FF \cL form feed
121 \n 10 0A LF \cJ line feed [2]
122 \r 13 0D CR \cM carriage return
123 \t 9 09 TAB \cI tab
124
125 [1] "\b" is the backspace character only inside a character class.
126 Outside a character class, "\b" alone is a
127 word-character/non-word-character boundary, and "\b{}" is some
128 other type of boundary.
129
130 [2] "\n" matches a logical newline. Perl converts between "\n" and your
131 OS's native newline character when reading from or writing to text
132 files.
133
134 Example
135
136 $str =~ /\t/; # Matches if $str contains a (horizontal) tab.
137
138 Control characters
139
140 "\c" is used to denote a control character; the character following
141 "\c" determines the value of the construct. For example the value of
142 "\cA" is chr(1), and the value of "\cb" is chr(2), etc. The gory
143 details are in "Regexp Quote-Like Operators" in perlop. A complete
144 list of what chr(1), etc. means for ASCII and EBCDIC platforms is in
145 "OPERATOR DIFFERENCES" in perlebcdic.
146
147 Note that "\c\" alone at the end of a regular expression (or doubled-
148 quoted string) is not valid. The backslash must be followed by another
149 character. That is, "\c\X" means "chr(28) . 'X'" for all characters X.
150
151 To write platform-independent code, you must use "\N{NAME}" instead,
152 like "\N{ESCAPE}" or "\N{U+001B}", see charnames.
153
154 Mnemonic: control character.
155
156 Example
157
158 $str =~ /\cK/; # Matches if $str contains a vertical tab (control-K).
159
160 Named or numbered characters and character sequences
161
162 Unicode characters have a Unicode name and numeric code point (ordinal)
163 value. Use the "\N{}" construct to specify a character by either of
164 these values. Certain sequences of characters also have names.
165
166 To specify by name, the name of the character or character sequence
167 goes between the curly braces.
168
169 To specify a character by Unicode code point, use the form "\N{U+code
170 point}", where code point is a number in hexadecimal that gives the
171 code point that Unicode has assigned to the desired character. It is
172 customary but not required to use leading zeros to pad the number to 4
173 digits. Thus "\N{U+0041}" means "LATIN CAPITAL LETTER A", and you will
174 rarely see it written without the two leading zeros. "\N{U+0041}"
175 means "A" even on EBCDIC machines (where the ordinal value of "A" is
176 not 0x41).
177
178 It is even possible to give your own names to characters and character
179 sequences by using the charnames module. These custom names are
180 lexically scoped, and so a given code point may have different names in
181 different scopes. The name used is what is in effect at the time the
182 "\N{}" is expanded. For patterns in double-quotish context, that means
183 at the time the pattern is parsed. But for patterns that are
184 delimitted by single quotes, the expansion is deferred until pattern
185 compilation time, which may very well have a different "charnames"
186 translator in effect.
187
188 (There is an expanded internal form that you may see in debug output:
189 "\N{U+code point.code point...}". The "..." means any number of these
190 code points separated by dots. This represents the sequence formed by
191 the characters. This is an internal form only, subject to change, and
192 you should not try to use it yourself.)
193
194 Mnemonic: Named character.
195
196 Note that a character or character sequence expressed as a named or
197 numbered character is considered a character without special meaning by
198 the regex engine, and will match "as is".
199
200 Example
201
202 $str =~ /\N{THAI CHARACTER SO SO}/; # Matches the Thai SO SO character
203
204 use charnames 'Cyrillic'; # Loads Cyrillic names.
205 $str =~ /\N{ZHE}\N{KA}/; # Match "ZHE" followed by "KA".
206
207 Octal escapes
208
209 There are two forms of octal escapes. Each is used to specify a
210 character by its code point specified in octal notation.
211
212 One form, available starting in Perl 5.14 looks like "\o{...}", where
213 the dots represent one or more octal digits. It can be used for any
214 Unicode character.
215
216 It was introduced to avoid the potential problems with the other form,
217 available in all Perls. That form consists of a backslash followed by
218 three octal digits. One problem with this form is that it can look
219 exactly like an old-style backreference (see "Disambiguation rules
220 between old-style octal escapes and backreferences" below.) You can
221 avoid this by making the first of the three digits always a zero, but
222 that makes \077 the largest code point specifiable.
223
224 In some contexts, a backslash followed by two or even one octal digits
225 may be interpreted as an octal escape, sometimes with a warning, and
226 because of some bugs, sometimes with surprising results. Also, if you
227 are creating a regex out of smaller snippets concatenated together, and
228 you use fewer than three digits, the beginning of one snippet may be
229 interpreted as adding digits to the ending of the snippet before it.
230 See "Absolute referencing" for more discussion and examples of the
231 snippet problem.
232
233 Note that a character expressed as an octal escape is considered a
234 character without special meaning by the regex engine, and will match
235 "as is".
236
237 To summarize, the "\o{}" form is always safe to use, and the other form
238 is safe to use for code points through \077 when you use exactly three
239 digits to specify them.
240
241 Mnemonic: 0ctal or octal.
242
243 Examples (assuming an ASCII platform)
244
245 $str = "Perl";
246 $str =~ /\o{120}/; # Match, "\120" is "P".
247 $str =~ /\120/; # Same.
248 $str =~ /\o{120}+/; # Match, "\120" is "P",
249 # it's repeated at least once.
250 $str =~ /\120+/; # Same.
251 $str =~ /P\053/; # No match, "\053" is "+" and taken literally.
252 /\o{23073}/ # Black foreground, white background smiling face.
253 /\o{4801234567}/ # Raises a warning, and yields chr(4).
254
255 Disambiguation rules between old-style octal escapes and backreferences
256
257 Octal escapes of the "\000" form outside of bracketed character classes
258 potentially clash with old-style backreferences (see "Absolute
259 referencing" below). They both consist of a backslash followed by
260 numbers. So Perl has to use heuristics to determine whether it is a
261 backreference or an octal escape. Perl uses the following rules to
262 disambiguate:
263
264 1. If the backslash is followed by a single digit, it's a
265 backreference.
266
267 2. If the first digit following the backslash is a 0, it's an octal
268 escape.
269
270 3. If the number following the backslash is N (in decimal), and Perl
271 already has seen N capture groups, Perl considers this a
272 backreference. Otherwise, it considers it an octal escape. If N
273 has more than three digits, Perl takes only the first three for the
274 octal escape; the rest are matched as is.
275
276 my $pat = "(" x 999;
277 $pat .= "a";
278 $pat .= ")" x 999;
279 /^($pat)\1000$/; # Matches 'aa'; there are 1000 capture groups.
280 /^$pat\1000$/; # Matches 'a@0'; there are 999 capture groups
281 # and \1000 is seen as \100 (a '@') and a '0'.
282
283 You can force a backreference interpretation always by using the
284 "\g{...}" form. You can the force an octal interpretation always by
285 using the "\o{...}" form, or for numbers up through \077 (= 63
286 decimal), by using three digits, beginning with a "0".
287
288 Hexadecimal escapes
289
290 Like octal escapes, there are two forms of hexadecimal escapes, but
291 both start with the sequence "\x". This is followed by either exactly
292 two hexadecimal digits forming a number, or a hexadecimal number of
293 arbitrary length surrounded by curly braces. The hexadecimal number is
294 the code point of the character you want to express.
295
296 Note that a character expressed as one of these escapes is considered a
297 character without special meaning by the regex engine, and will match
298 "as is".
299
300 Mnemonic: hexadecimal.
301
302 Examples (assuming an ASCII platform)
303
304 $str = "Perl";
305 $str =~ /\x50/; # Match, "\x50" is "P".
306 $str =~ /\x50+/; # Match, "\x50" is "P", it is repeated at least once
307 $str =~ /P\x2B/; # No match, "\x2B" is "+" and taken literally.
308
309 /\x{2603}\x{2602}/ # Snowman with an umbrella.
310 # The Unicode character 2603 is a snowman,
311 # the Unicode character 2602 is an umbrella.
312 /\x{263B}/ # Black smiling face.
313 /\x{263b}/ # Same, the hex digits A - F are case insensitive.
314
315 Modifiers
316 A number of backslash sequences have to do with changing the character,
317 or characters following them. "\l" will lowercase the character
318 following it, while "\u" will uppercase (or, more accurately,
319 titlecase) the character following it. They provide functionality
320 similar to the functions "lcfirst" and "ucfirst".
321
322 To uppercase or lowercase several characters, one might want to use
323 "\L" or "\U", which will lowercase/uppercase all characters following
324 them, until either the end of the pattern or the next occurrence of
325 "\E", whichever comes first. They provide functionality similar to what
326 the functions "lc" and "uc" provide.
327
328 "\Q" is used to quote (disable) pattern metacharacters, up to the next
329 "\E" or the end of the pattern. "\Q" adds a backslash to any character
330 that could have special meaning to Perl. In the ASCII range, it quotes
331 every character that isn't a letter, digit, or underscore. See
332 "quotemeta" in perlfunc for details on what gets quoted for non-ASCII
333 code points. Using this ensures that any character between "\Q" and
334 "\E" will be matched literally, not interpreted as a metacharacter by
335 the regex engine.
336
337 "\F" can be used to casefold all characters following, up to the next
338 "\E" or the end of the pattern. It provides the functionality similar
339 to the "fc" function.
340
341 Mnemonic: Lowercase, Uppercase, Fold-case, Quotemeta, End.
342
343 Examples
344
345 $sid = "sid";
346 $greg = "GrEg";
347 $miranda = "(Miranda)";
348 $str =~ /\u$sid/; # Matches 'Sid'
349 $str =~ /\L$greg/; # Matches 'greg'
350 $str =~ /\Q$miranda\E/; # Matches '(Miranda)', as if the pattern
351 # had been written as /\(Miranda\)/
352
353 Character classes
354 Perl regular expressions have a large range of character classes. Some
355 of the character classes are written as a backslash sequence. We will
356 briefly discuss those here; full details of character classes can be
357 found in perlrecharclass.
358
359 "\w" is a character class that matches any single word character
360 (letters, digits, Unicode marks, and connector punctuation (like the
361 underscore)). "\d" is a character class that matches any decimal
362 digit, while the character class "\s" matches any whitespace character.
363 New in perl 5.10.0 are the classes "\h" and "\v" which match horizontal
364 and vertical whitespace characters.
365
366 The exact set of characters matched by "\d", "\s", and "\w" varies
367 depending on various pragma and regular expression modifiers. It is
368 possible to restrict the match to the ASCII range by using the "/a"
369 regular expression modifier. See perlrecharclass.
370
371 The uppercase variants ("\W", "\D", "\S", "\H", and "\V") are character
372 classes that match, respectively, any character that isn't a word
373 character, digit, whitespace, horizontal whitespace, or vertical
374 whitespace.
375
376 Mnemonics: word, digit, space, horizontal, vertical.
377
378 Unicode classes
379
380 "\pP" (where "P" is a single letter) and "\p{Property}" are used to
381 match a character that matches the given Unicode property; properties
382 include things like "letter", or "thai character". Capitalizing the
383 sequence to "\PP" and "\P{Property}" make the sequence match a
384 character that doesn't match the given Unicode property. For more
385 details, see "Backslash sequences" in perlrecharclass and "Unicode
386 Character Properties" in perlunicode.
387
388 Mnemonic: property.
389
390 Referencing
391 If capturing parenthesis are used in a regular expression, we can refer
392 to the part of the source string that was matched, and match exactly
393 the same thing. There are three ways of referring to such
394 backreference: absolutely, relatively, and by name.
395
396 Absolute referencing
397
398 Either "\gN" (starting in Perl 5.10.0), or "\N" (old-style) where N is
399 a positive (unsigned) decimal number of any length is an absolute
400 reference to a capturing group.
401
402 N refers to the Nth set of parentheses, so "\gN" refers to whatever has
403 been matched by that set of parentheses. Thus "\g1" refers to the
404 first capture group in the regex.
405
406 The "\gN" form can be equivalently written as "\g{N}" which avoids
407 ambiguity when building a regex by concatenating shorter strings.
408 Otherwise if you had a regex "qr/$a$b/", and $a contained "\g1", and $b
409 contained "37", you would get "/\g137/" which is probably not what you
410 intended.
411
412 In the "\N" form, N must not begin with a "0", and there must be at
413 least N capturing groups, or else N is considered an octal escape (but
414 something like "\18" is the same as "\0018"; that is, the octal escape
415 "\001" followed by a literal digit "8").
416
417 Mnemonic: group.
418
419 Examples
420
421 /(\w+) \g1/; # Finds a duplicated word, (e.g. "cat cat").
422 /(\w+) \1/; # Same thing; written old-style.
423 /(.)(.)\g2\g1/; # Match a four letter palindrome (e.g. "ABBA").
424
425 Relative referencing
426
427 "\g-N" (starting in Perl 5.10.0) is used for relative addressing. (It
428 can be written as "\g{-N}".) It refers to the Nth group before the
429 "\g{-N}".
430
431 The big advantage of this form is that it makes it much easier to write
432 patterns with references that can be interpolated in larger patterns,
433 even if the larger pattern also contains capture groups.
434
435 Examples
436
437 /(A) # Group 1
438 ( # Group 2
439 (B) # Group 3
440 \g{-1} # Refers to group 3 (B)
441 \g{-3} # Refers to group 1 (A)
442 )
443 /x; # Matches "ABBA".
444
445 my $qr = qr /(.)(.)\g{-2}\g{-1}/; # Matches 'abab', 'cdcd', etc.
446 /$qr$qr/ # Matches 'ababcdcd'.
447
448 Named referencing
449
450 "\g{name}" (starting in Perl 5.10.0) can be used to back refer to a
451 named capture group, dispensing completely with having to think about
452 capture buffer positions.
453
454 To be compatible with .Net regular expressions, "\g{name}" may also be
455 written as "\k{name}", "\k<name>" or "\k'name'".
456
457 To prevent any ambiguity, name must not start with a digit nor contain
458 a hyphen.
459
460 Examples
461
462 /(?<word>\w+) \g{word}/ # Finds duplicated word, (e.g. "cat cat")
463 /(?<word>\w+) \k{word}/ # Same.
464 /(?<word>\w+) \k<word>/ # Same.
465 /(?<letter1>.)(?<letter2>.)\g{letter2}\g{letter1}/
466 # Match a four letter palindrome (e.g. "ABBA")
467
468 Assertions
469 Assertions are conditions that have to be true; they don't actually
470 match parts of the substring. There are six assertions that are written
471 as backslash sequences.
472
473 \A "\A" only matches at the beginning of the string. If the "/m"
474 modifier isn't used, then "/\A/" is equivalent to "/^/". However,
475 if the "/m" modifier is used, then "/^/" matches internal newlines,
476 but the meaning of "/\A/" isn't changed by the "/m" modifier. "\A"
477 matches at the beginning of the string regardless whether the "/m"
478 modifier is used.
479
480 \z, \Z
481 "\z" and "\Z" match at the end of the string. If the "/m" modifier
482 isn't used, then "/\Z/" is equivalent to "/$/"; that is, it matches
483 at the end of the string, or one before the newline at the end of
484 the string. If the "/m" modifier is used, then "/$/" matches at
485 internal newlines, but the meaning of "/\Z/" isn't changed by the
486 "/m" modifier. "\Z" matches at the end of the string (or just
487 before a trailing newline) regardless whether the "/m" modifier is
488 used.
489
490 "\z" is just like "\Z", except that it does not match before a
491 trailing newline. "\z" matches at the end of the string only,
492 regardless of the modifiers used, and not just before a newline.
493 It is how to anchor the match to the true end of the string under
494 all conditions.
495
496 \G "\G" is usually used only in combination with the "/g" modifier. If
497 the "/g" modifier is used and the match is done in scalar context,
498 Perl remembers where in the source string the last match ended, and
499 the next time, it will start the match from where it ended the
500 previous time.
501
502 "\G" matches the point where the previous match on that string
503 ended, or the beginning of that string if there was no previous
504 match.
505
506 Mnemonic: Global.
507
508 \b{}, \b, \B{}, \B
509 "\b{...}", available starting in v5.22, matches a boundary (between
510 two characters, or before the first character of the string, or
511 after the final character of the string) based on the Unicode rules
512 for the boundary type specified inside the braces. The boundary
513 types are given a few paragraphs below. "\B{...}" matches at any
514 place between characters where "\b{...}" of the same type doesn't
515 match.
516
517 "\b" when not immediately followed by a "{" matches at any place
518 between a word (something matched by "\w") and a non-word character
519 ("\W"); "\B" when not immediately followed by a "{" matches at any
520 place between characters where "\b" doesn't match. To get better
521 word matching of natural language text, see "\b{wb}" below.
522
523 "\b" and "\B" assume there's a non-word character before the
524 beginning and after the end of the source string; so "\b" will
525 match at the beginning (or end) of the source string if the source
526 string begins (or ends) with a word character. Otherwise, "\B" will
527 match.
528
529 Do not use something like "\b=head\d\b" and expect it to match the
530 beginning of a line. It can't, because for there to be a boundary
531 before the non-word "=", there must be a word character immediately
532 previous. All plain "\b" and "\B" boundary determinations look for
533 word characters alone, not for non-word characters nor for string
534 ends. It may help to understand how "\b" and "\B" work by equating
535 them as follows:
536
537 \b really means (?:(?<=\w)(?!\w)|(?<!\w)(?=\w))
538 \B really means (?:(?<=\w)(?=\w)|(?<!\w)(?!\w))
539
540 In contrast, "\b{...}" and "\B{...}" may or may not match at the
541 beginning and end of the line, depending on the boundary type.
542 These implement the Unicode default boundaries, specified in
543 <https://www.unicode.org/reports/tr14/> and
544 <https://www.unicode.org/reports/tr29/>. The boundary types are:
545
546 "\b{gcb}" or "\b{g}"
547 This matches a Unicode "Grapheme Cluster Boundary". (Actually
548 Perl always uses the improved "extended" grapheme cluster").
549 These are explained below under ""\X"". In fact, "\X" is
550 another way to get the same functionality. It is equivalent to
551 "/.+?\b{gcb}/". Use whichever is most convenient for your
552 situation.
553
554 "\b{lb}"
555 This matches according to the default Unicode Line Breaking
556 Algorithm (<https://www.unicode.org/reports/tr14/>), as
557 customized in that document (Example 7 of revision 35
558 <https://www.unicode.org/reports/tr14/tr14-35.html#Example7>)
559 for better handling of numeric expressions.
560
561 This is suitable for many purposes, but the Unicode::LineBreak
562 module is available on CPAN that provides many more features,
563 including customization.
564
565 "\b{sb}"
566 This matches a Unicode "Sentence Boundary". This is an aid to
567 parsing natural language sentences. It gives good, but
568 imperfect results. For example, it thinks that "Mr. Smith" is
569 two sentences. More details are at
570 <https://www.unicode.org/reports/tr29/>. Note also that it
571 thinks that anything matching "\R" (except form feed and
572 vertical tab) is a sentence boundary. "\b{sb}" works with text
573 designed for word-processors which wrap lines automatically for
574 display, but hard-coded line boundaries are considered to be
575 essentially the ends of text blocks (paragraphs really), and
576 hence the ends of sentences. "\b{sb}" doesn't do well with
577 text containing embedded newlines, like the source text of the
578 document you are reading. Such text needs to be preprocessed
579 to get rid of the line separators before looking for sentence
580 boundaries. Some people view this as a bug in the Unicode
581 standard, and this behavior is quite subject to change in
582 future Perl versions.
583
584 "\b{wb}"
585 This matches a Unicode "Word Boundary", but tailored to Perl
586 expectations. This gives better (though not perfect) results
587 for natural language processing than plain "\b" (without
588 braces) does. For example, it understands that apostrophes can
589 be in the middle of words and that parentheses aren't (see the
590 examples below). More details are at
591 <https://www.unicode.org/reports/tr29/>.
592
593 The current Unicode definition of a Word Boundary matches
594 between every white space character. Perl tailors this,
595 starting in version 5.24, to generally not break up spans of
596 white space, just as plain "\b" has always functioned. This
597 allows "\b{wb}" to be a drop-in replacement for "\b", but with
598 generally better results for natural language processing. (The
599 exception to this tailoring is when a span of white space is
600 immediately followed by something like U+0303, COMBINING TILDE.
601 If the final space character in the span is a horizontal white
602 space, it is broken out so that it attaches instead to the
603 combining character. To be precise, if a span of white space
604 that ends in a horizontal space has the character immediately
605 following it have any of the Word Boundary property values
606 "Extend", "Format" or "ZWJ", the boundary between the final
607 horizontal space character and the rest of the span matches
608 "\b{wb}". In all other cases the boundary between two white
609 space characters matches "\B{wb}".)
610
611 It is important to realize when you use these Unicode boundaries,
612 that you are taking a risk that a future version of Perl which
613 contains a later version of the Unicode Standard will not work
614 precisely the same way as it did when your code was written. These
615 rules are not considered stable and have been somewhat more subject
616 to change than the rest of the Standard. Unicode reserves the
617 right to change them at will, and Perl reserves the right to update
618 its implementation to Unicode's new rules. In the past, some
619 changes have been because new characters have been added to the
620 Standard which have different characteristics than all previous
621 characters, so new rules are formulated for handling them. These
622 should not cause any backward compatibility issues. But some
623 changes have changed the treatment of existing characters because
624 the Unicode Technical Committee has decided that the change is
625 warranted for whatever reason. This could be to fix a bug, or
626 because they think better results are obtained with the new rule.
627
628 It is also important to realize that these are default boundary
629 definitions, and that implementations may wish to tailor the
630 results for particular purposes and locales. For example, some
631 languages, such as Japanese and Thai, require dictionary lookup to
632 accurately determine word boundaries.
633
634 Mnemonic: boundary.
635
636 Examples
637
638 "cat" =~ /\Acat/; # Match.
639 "cat" =~ /cat\Z/; # Match.
640 "cat\n" =~ /cat\Z/; # Match.
641 "cat\n" =~ /cat\z/; # No match.
642
643 "cat" =~ /\bcat\b/; # Matches.
644 "cats" =~ /\bcat\b/; # No match.
645 "cat" =~ /\bcat\B/; # No match.
646 "cats" =~ /\bcat\B/; # Match.
647
648 while ("cat dog" =~ /(\w+)/g) {
649 print $1; # Prints 'catdog'
650 }
651 while ("cat dog" =~ /\G(\w+)/g) {
652 print $1; # Prints 'cat'
653 }
654
655 my $s = "He said, \"Is pi 3.14? (I'm not sure).\"";
656 print join("|", $s =~ m/ ( .+? \b ) /xg), "\n";
657 print join("|", $s =~ m/ ( .+? \b{wb} ) /xg), "\n";
658 prints
659 He| |said|, "|Is| |pi| |3|.|14|? (|I|'|m| |not| |sure
660 He| |said|,| |"|Is| |pi| |3.14|?| |(|I'm| |not| |sure|)|.|"
661
662 Misc
663 Here we document the backslash sequences that don't fall in one of the
664 categories above. These are:
665
666 \K This appeared in perl 5.10.0. Anything matched left of "\K" is not
667 included in $&, and will not be replaced if the pattern is used in
668 a substitution. This lets you write "s/PAT1 \K PAT2/REPL/x" instead
669 of "s/(PAT1) PAT2/${1}REPL/x" or "s/(?<=PAT1) PAT2/REPL/x".
670
671 Mnemonic: Keep.
672
673 \N This feature, available starting in v5.12, matches any character
674 that is not a newline. It is a short-hand for writing "[^\n]", and
675 is identical to the "." metasymbol, except under the "/s" flag,
676 which changes the meaning of ".", but not "\N".
677
678 Note that "\N{...}" can mean a named or numbered character .
679
680 Mnemonic: Complement of \n.
681
682 \R "\R" matches a generic newline; that is, anything considered a
683 linebreak sequence by Unicode. This includes all characters matched
684 by "\v" (vertical whitespace), and the multi character sequence
685 "\x0D\x0A" (carriage return followed by a line feed, sometimes
686 called the network newline; it's the end of line sequence used in
687 Microsoft text files opened in binary mode). "\R" is equivalent to
688 "(?>\x0D\x0A|\v)". (The reason it doesn't backtrack is that the
689 sequence is considered inseparable. That means that
690
691 "\x0D\x0A" =~ /^\R\x0A$/ # No match
692
693 fails, because the "\R" matches the entire string, and won't
694 backtrack to match just the "\x0D".) Since "\R" can match a
695 sequence of more than one character, it cannot be put inside a
696 bracketed character class; "/[\R]/" is an error; use "\v" instead.
697 "\R" was introduced in perl 5.10.0.
698
699 Note that this does not respect any locale that might be in effect;
700 it matches according to the platform's native character set.
701
702 Mnemonic: none really. "\R" was picked because PCRE already uses
703 "\R", and more importantly because Unicode recommends such a
704 regular expression metacharacter, and suggests "\R" as its
705 notation.
706
707 \X This matches a Unicode extended grapheme cluster.
708
709 "\X" matches quite well what normal (non-Unicode-programmer) usage
710 would consider a single character. As an example, consider a G
711 with some sort of diacritic mark, such as an arrow. There is no
712 such single character in Unicode, but one can be composed by using
713 a G followed by a Unicode "COMBINING UPWARDS ARROW BELOW", and
714 would be displayed by Unicode-aware software as if it were a single
715 character.
716
717 The match is greedy and non-backtracking, so that the cluster is
718 never broken up into smaller components.
719
720 See also "\b{gcb}".
721
722 Mnemonic: eXtended Unicode character.
723
724 Examples
725
726 $str =~ s/foo\Kbar/baz/g; # Change any 'bar' following a 'foo' to 'baz'
727 $str =~ s/(.)\K\g1//g; # Delete duplicated characters.
728
729 "\n" =~ /^\R$/; # Match, \n is a generic newline.
730 "\r" =~ /^\R$/; # Match, \r is a generic newline.
731 "\r\n" =~ /^\R$/; # Match, \r\n is a generic newline.
732
733 "P\x{307}" =~ /^\X$/ # \X matches a P with a dot above.
734
735
736
737perl v5.32.1 2021-05-31 PERLREBACKSLASH(1)