1PERLREBACKSLASH(1)     Perl Programmers Reference Guide     PERLREBACKSLASH(1)
2
3
4

NAME

6       perlrebackslash - Perl Regular Expression Backslash Sequences and
7       Escapes
8

DESCRIPTION

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