PERLREBACKSLASH(1perl)

πŸ“¦
version 5.44.0 Β· 2 versions
, in arch rolling

✨ perlrebackslash ✨ Perl Regular Expression Backslash Sequences and Escapes πŸŽ€

πŸ’– NAME πŸ’–

perlrebackslash β€” Perl Regular Expression Backslash Sequences and Escapes πŸ’…

πŸ¦‹ DESCRIPTION πŸ¦‹

okay bestie so if you want the top-level tea on Perl regular expressions, that lives in perlre. πŸ’–

This doc? It's the backslash bible. It walks through every backslash and escape sequence: first it explains what the backslash is even doing with its life, then it lists every sequence that has special meaning in Perl regexes (in alphabetical order, no cap), and then it describes each one.

Most of these lil sequences get the full deep-dive treatment in other docs, so the whole point of this page is basically a quick-reference cheat sheet for all the backslash and escape sequences. 🌈


✨ The backslash ✨

Inside a regex, the backslash has exactly two jobs and it's serving both:

  • it can take away the special meaning of whatever character comes right after it (like, \| matches a literal vertical bar β€” it's not an alternation, bestie), or
  • it can be the start of a backslash or escape sequence. πŸ‘‘

The rules for figuring out which one you're getting are actually mad simple: if the character right after the backslash is an ASCII punctuation (non-word) character β€” meaning literally anything that is not a letter, digit, or underscore β€” then the backslash just strips the special meaning off that character. done. πŸ’…

But if the character after the backslash is an ASCII letter or an ASCII digit, then the sequence might be special. If it is, it's listed below ⬇️. A few letters haven't been claimed yet, so escaping them with a backslash doesn't actually turn them into anything special. However β€” a future version of Perl may decide to give those letters a special meaning, so if you've got warnings turned on, Perl will yell at you when you use such a sequence. πŸ™ˆ

Here's the comforting part though: it is guaranteed that backslash or escape sequences will never have a punctuation character following the backslash β€” not now, and not in any future version of Perl 5. So it is totally safe to slap a backslash in front of a non-word character. 🫢

Also, heads up: the backslash itself is special. If you wanna match a backslash, you have to escape the backslash with a backslash β€” /\\/ matches a single backslash.

And one more thing 😭 β€” if a character inside the pattern proper is the same as the pattern's closing delimiter, it has to be escaped so it keeps its normal meaning and doesn't get mistaken for the end of the pattern. Which means: if that character is also a metacharacter, escaping it makes Perl treat it as that metacharacter. To match it literally, wrap the escaped sequence in square brackets:

m...       # Syntax error!
m.\..      # Normal meaning: matches any character but \n
m.[.].     # Syntax error!
m.[\.].    # Matches a literal dot "."

None of this works if the delimiter is a backslash, though. Like, at all:

m\\\       # Syntax error!
m\\\\      # Syntax error!
m\[\]\     # Syntax error!
m\[\\]\    # Syntax error!

Throwing more backslashes at it does not help. So don't use backslash as a delimiter and then expect to have any backslash inside the pattern. Just don't. πŸ’€

Escaping an ASCII letter or digit inside a pattern that's delimited by that same character does not turn the sequence into one with special meaning. Example era:

qr w\ww

That matches a literal "w" character. It does not match what \w normally matches. So like, it doesn't match a word character, and there is no combo of backslashes and/or brackets you can add that'll change that. Using "w" as your pattern delimiter straight up takes away the ability to use \w inside and have it mean the special thing. Same energy applies to all the other similar cases.

Finally, like we said above, using a backslash + alphabetic letter sequence that Perl doesn't currently recognize as special normally raises a warning. That warning gets suppressed if the escaped character is also the delimiter:

qr C\CC

\C matches a literal "C" character, and doesn't warn. πŸŽ€

See also "Gory details of parsing quoted constructs" in perlop.


πŸ”₯ All the sequences and escapes πŸ”₯

Those that are not usable inside a bracketed character class (like [\da-z]) get marked as "Not in []." β€” noted below, bestie:

  • \000 β€” Octal escape sequence. See also \o{}.
  • \1 β€” Absolute backreference. Not in [].
  • \a β€” Alert or bell.
  • \A β€” Beginning of string. Not in [].
  • \b{}, \b β€” Boundary. (\b is a backspace in []).
  • \B{}, \B β€” Not a boundary. Not in [].
  • \cX β€” Control-X.
  • \d β€” Match any digit character.
  • \D β€” Match any character that isn't a digit.
  • \e β€” Escape character.
  • \E β€” Turn off \Q, \L and \U processing. Not in [] unless is terminating one of those also in the [].
  • \f β€” Form feed.
  • \F β€” Foldcase till \E.
  • \g{}, \g1 β€” Named, absolute or relative backreference. Not in [].
  • \G β€” Pos assertion. Not in [].
  • \h β€” Match any horizontal whitespace character.
  • \H β€” Match any character that isn't horizontal whitespace.
  • \k{}, \k<>, \k'' β€” Named backreference. Not in [].
  • \K β€” Keep the stuff left of \K. Not in [].
  • \l β€” Lowercase next character.
  • \L β€” Lowercase till \E.
  • \n β€” (Logical) newline character.
  • \N β€” Match any character but newline. Not in [].
  • \N{} β€” Named or numbered (Unicode) character or sequence.
  • \o{} β€” Octal escape sequence.
  • \p{}, \pP β€” Match any character with the given Unicode property.
  • \P{}, \PP β€” Match any character without the given property.
  • \Q β€” Quote (disable) pattern metacharacters till \E. (Also called "escape".) Not in [] unless there's a terminating \E before the ']';
  • \r β€” Return character.
  • \R β€” Generic new line. Not in [].
  • \s β€” Match any whitespace character.
  • \S β€” Match any character that isn't a whitespace.
  • \t β€” Tab character.
  • \u β€” Titlecase next character.
  • \U β€” Uppercase till \E.
  • \v β€” Match any vertical whitespace character.
  • \V β€” Match any character that isn't vertical whitespace
  • \w β€” Match any word character.
  • \W β€” Match any character that isn't a word character.
  • \x{}, \x00 β€” Hexadecimal escape sequence.
  • \X β€” Unicode "extended grapheme cluster". Not in [].
  • \z β€” End of string. Not in [].
  • \Z β€” End of string. Not in [].

🌸 Character Escapes 🌸

✨ Fixed characters ✨

A handful of characters get their own dedicated character escape β€” a whole little glow-up, iconic. The list below shows them, plus their ASCII code points (both decimal and hex), their ASCII name, the control escape on ASCII platforms, and a short description. (For EBCDIC platforms, go look at "OPERATOR DIFFERENCES" in perlebcdic.) πŸ’œ

  • \a β€” code point 7 (dec) / 07 (hex), ASCII name BEL, control escape \cG: alert or bell
  • \b β€” code point 8 (dec) / 08 (hex), ASCII name BS, control escape \cH: backspace [1]
  • \e β€” code point 27 (dec) / 1B (hex), ASCII name ESC, control escape \c[: escape character
  • \f β€” code point 12 (dec) / 0C (hex), ASCII name FF, control escape \cL: form feed
  • \n β€” code point 10 (dec) / 0A (hex), ASCII name LF, control escape \cJ: line feed [2]
  • \r β€” code point 13 (dec) / 0D (hex), ASCII name CR, control escape \cM: carriage return
  • \t β€” code point 9 (dec) / 09 (hex), ASCII name TAB, control escape \cI: tab

[1] \b is the backspace character only inside a character class. Outside a character class, \b alone is a word-character/non-word-character boundary, and \b{} is some other type of boundary.

[2] \n matches a logical newline. Perl converts between \n and your OS's native newline character when reading from or writing to text files.

Example πŸ“

$str =~ /\t/;   # Matches if $str contains a (horizontal) tab.

πŸŽ€ Control characters πŸŽ€

\c is how you denote a control character; whatever character follows the \c determines the value of the whole construct. For example, the value of \cA is chr(1), and the value of \cb is chr(2), etc. The gory details live in "Regexp Quote-Like Operators" in perlop. And a complete list of what chr(1), etc. means for ASCII and EBCDIC platforms is in "OPERATOR DIFFERENCES" in perlebcdic. πŸ”₯

⚠️ Note that \c\ alone at the end of a regular expression (or a doubled-quoted string) is not valid. The backslash must be followed by another character. That is, \c\X means chr(28) . 'X' for all characters X.

If you want platform-independent code, you must use \N{NAME} instead β€” like \N{ESCAPE} or \N{U+001B} β€” see charnames.

Mnemonic: control character. πŸ‘‘

Example

$str =~ /\cK/;  # Matches if $str contains a vertical tab (control-K).

πŸ’… Named or numbered characters and character sequences πŸ’…

Unicode characters have a Unicode name and a numeric code point (ordinal) value. Use the \N{} construct to specify a character by either of those two things. And plot twist β€” certain sequences of characters have names too. πŸ¦‹

To specify by name, the name of the character or character sequence goes between the curly braces.

To specify a character by Unicode code point, use the form \N{U+code point}, where code point is a hexadecimal number giving the code point Unicode assigned to the character you want. It's customary β€” but not required β€” to use leading zeros to pad the number to 4 digits. So \N{U+0041} means "LATIN CAPITAL LETTER A", and you'll rarely see it written without those two leading zeros. And \N{U+0041} means "A" even on EBCDIC machines (where the ordinal value of "A" is not 0x41). 🀯

Blanks can be freely inserted adjacent to β€” but within β€” the braces enclosing the name or code point. So \N{ U+0041 } is perfectly legal, bestie. ✨

It's even possible to give your own names to characters and character sequences by using the charnames module. These custom names are lexically scoped, so a given code point may have different names in different scopes. The name that's used is whatever is in effect at the time the \N{} gets expanded. For patterns in double-quotish context, that means at the time the pattern is parsed. But for patterns delimited by single quotes, the expansion is deferred until pattern compilation time, which may very well have a totally different "charnames" translator in effect. 😭

(There's an expanded internal form you might see in debug output: \N{U+code point.code point...}. The ... means any number of those code points separated by dots. This represents the sequence formed by the characters. It's an internal form only, subject to change, and you should not try to use it yourself.) πŸ™ˆ

Mnemonic: Named character. πŸ’–

Note that a character or character sequence expressed as a named or numbered character is considered a character without special meaning by the regex engine, and will match "as is".

Example

$str =~ /\N{THAI CHARACTER SO SO}/;  # Matches the Thai SO SO character
use charnames 'Cyrillic';            # Loads Cyrillic names.
$str =~ /\N{ZHE}\N{KA}/;             # Match "ZHE" followed by "KA".

🌸 Octal escapes 🌸

Bestie, there are two forms of octal escapes, and both of them let you name a character by its code point written out in base 8. Iconic behavior honestly.

One form β€” the new girl, available starting in Perl 5.14 β€” looks like \o{...}, where those dots are standing in for one or more octal digits. It works for literally any Unicode character. Main character energy.

The other form is the old money one, available in all Perls: a backslash followed by exactly three octal digits. It got a glow-up replacement because it has a real problem β€” it can look exactly like an old-style backreference (peep "Disambiguation rules between old-style octal escapes and backreferences" below πŸ‘€). You can dodge that by always making the first of those three digits a zero, but then \077 is the biggest code point you can even specify. So that's the trade, bestie.

And in some contexts, a backslash followed by two or even one octal digit may get read as an octal escape β€” sometimes with a warning, and because of some bugs, sometimes with genuinely surprising results. 😭

Also, if you're building a regex out of smaller snippets concatenated together and you use fewer than three digits, the beginning of one snippet can get read as adding digits onto the end of the snippet before it. That's the snippet problem β€” go read "Absolute referencing" for the full discussion and examples.

Note that a character expressed as an octal escape is considered a character without special meaning by the regex engine, and it will match "as is".

To summarize, fr fr:

  • \o{} is always safe to use.
  • The other form is safe for code points through \077 when you use exactly three digits to specify them.

Mnemonic: 0ctal or octal. The zero is the whole point, iykyk. πŸ’…

Examples (assuming an ASCII platform):

$str = "Perl";
$str =~ /\o{120}/;  # Match, "\120" is "P".
$str =~ /\120/;     # Same.
$str =~ /\o{120}+/; # Match, "\120" is "P",
                    # it's repeated at least once.
$str =~ /\120+/;    # Same.
$str =~ /P\053/;    # No match, "\053" is "+" and taken literally.
/\o{23073}/         # Black foreground, white background smiling face.
/\o{4801234567}/    # Raises a warning, and yields chr(4).
/\o{ 400}/          # LATIN CAPITAL LETTER A WITH MACRON
/\o{ 400 }/         # Same. These show blanks are allowed adjacent to
                    # the braces

✨ Disambiguation rules between old-style octal escapes and backreferences ✨

Octal escapes in the \000 form β€” outside of bracketed character classes β€” can potentially clash with old-style backreferences (again: "Absolute referencing" below). They're both just a backslash followed by numbers. So Perl has to run some heuristics to figure out which one you meant. No cap, here are the rules Perl uses to disambiguate:

  1. If the backslash is followed by a single digit, it's a backreference.
  2. If the first digit following the backslash is a 0, it's an octal escape.
  3. If the number following the backslash is N (in decimal), and Perl has already seen N capture groups, Perl considers this a backreference. Otherwise, it considers it an octal escape. If N has more than three digits, Perl takes only the first three for the octal escape; the rest are matched as is.
my $pat  = "(" x 999;
   $pat .= "a";
   $pat .= ")" x 999;
/^($pat)\1000$/;   #  Matches 'aa'; there are 1000 capture groups.
/^$pat\1000$/;     #  Matches 'a@0'; there are 999 capture groups
                   #  and \1000 is seen as \100 (a '@') and a '0'.

You can force the backreference reading always by using the \g{...} form. And you can force the octal reading always by using the \o{...} form β€” or, for numbers up through \077 (= 63 decimal), by using three digits beginning with a "0".


πŸ¦‹ Hexadecimal escapes πŸ¦‹

Like octal escapes, there are two forms of hexadecimal escapes, but both of them start with the sequence \x. After that comes either exactly two hexadecimal digits forming a number, or a hexadecimal number of arbitrary length surrounded by curly braces. That hexadecimal number is the code point of the character you're expressing. Slay.

Note that a character expressed as one of these escapes is considered a character without special meaning by the regex engine, and it will match "as is".

Mnemonic: hexadecimal. (she's self-explanatory, we love her πŸŽ€)

Examples (assuming an ASCII platform):

$str = "Perl";
$str =~ /\x50/;    # Match, "\x50" is "P".
$str =~ /\x50+/;   # Match, "\x50" is "P", it is repeated at least once
$str =~ /P\x2B/;   # No match, "\x2B" is "+" and taken literally.

/\x{2603}\x{2602}/ # Snowman with an umbrella.
                   # The Unicode character 2603 is a snowman,
                   # the Unicode character 2602 is an umbrella.
/\x{263B}/         # Black smiling face.
/\x{263b}/         # Same, the hex digits A - F are case insensitive.
/\x{ 263b }/       # Same, showing optional blanks adjacent to the
                   # braces

πŸ’œ Modifiers πŸ’œ

A whole bunch of backslash sequences are about changing the character β€” or characters β€” that come after them.

  • \l will lowercase the character following it.
  • \u will uppercase it (or, more accurately, titlecase it).
  • These two are basically giving lcfirst and ucfirst but in regex form.

Wanna do it to several characters? That's what \L and \U are for β€” they lowercase/uppercase every character following them, until either the end of the pattern or the next occurrence of \E, whichever comes first. They're serving lc and uc energy.

  • \Q is the quote/escape girlie β€” she disables pattern metacharacters, all the way up to the next \E or the end of the pattern. \Q adds a backslash to any character that could have special meaning to Perl. In the ASCII range, it quotes every character that isn't a letter, a digit, or an underscore. For the tea on what gets quoted for non-ASCII code points, see "quotemeta" in perlfunc. Using this guarantees that anything between \Q and \E gets matched literally, not read as a metacharacter by the regex engine.
  • \F casefolds all the characters following it, up to the next \E or the end of the pattern. It's doing what the fc function does.

Mnemonic: Lowercase, Uppercase, Fold-case, Quotemeta, End. 🧚

Examples:

$sid     = "sid";
$greg    = "GrEg";
$miranda = "(Miranda)";
$str     =~ /\u$sid/;        # Matches 'Sid'
$str     =~ /\L$greg/;       # Matches 'greg'
$str     =~ /\Q$miranda\E/;  # Matches '(Miranda)', as if the pattern
                             #   had been written as /\(Miranda\)/

🌈 Character classes 🌈

Perl regular expressions have a huge range of character classes, and some of them are written as backslash sequences. We're gonna skim those here β€” the full details of character classes live in perlrecharclass.

  • \w β€” matches any single word character (letters, digits, Unicode marks, and connector punctuation, like the underscore).
  • \d β€” matches any decimal digit.
  • \s β€” matches any whitespace character.
  • \h and \v β€” new in perl 5.10.0 β€” match horizontal and vertical whitespace characters.

The exact set of characters matched by \d, \s, and \w varies depending on various pragma and regular expression modifiers. You can restrict the match to the ASCII range by using the /a regular expression modifier. See perlrecharclass for more.

And the uppercase versions β€” \W, \D, \S, \H, and \V β€” are character classes that match, respectively, any character that isn't a word character, a digit, whitespace, horizontal whitespace, or vertical whitespace. Every queen needs her opposite. πŸ‘‘

Mnemonics: word, digit, space, horizontal, vertical.

⭐ Unicode classes ⭐

\pP (where "P" is a single letter) and \p{Property} are used to match a character that matches the given Unicode property. Properties include things like "letter" or "thai character". Capitalize the sequence to \PP and \P{Property} and it flips β€” now it matches a character that doesn't match that Unicode property. More details in "Backslash sequences" in perlrecharclass and "Unicode Character Properties" in perlunicode.

Mnemonic: property.


πŸ‘‘ Referencing πŸ‘‘

If capturing parenthesis are used in a regular expression, we can refer back to the part of the source string that got matched, and match exactly the same thing. There are three ways of referring to such a backreference: absolutely, relatively, and by name.

πŸ’– Absolute referencing πŸ’–

Either \gN (starting in Perl 5.10.0) or \N (old-style), where N is a positive (unsigned) decimal number of any length, is an absolute reference to a capturing group.

N refers to the Nth set of parentheses, so \gN refers to whatever has been matched by that set of parentheses. Thus \g1 refers to the first capture group in the regex. Periodt.

The \gN form can be equivalently written as \g{N}, which avoids ambiguity when you're building a regex by concatenating shorter strings. Otherwise, say you had a regex qr/$x$y/, and $x contained \g1, and $y contained 37 β€” you'd get /\g137/, which is probably not what you were going for, bestie. πŸ™ˆ

In the \N form, N must not begin with a "0", and there must be at least N capturing groups, or else N is considered an octal escape (but something like \18 is the same as \0018; that is, the octal escape \001 followed by a literal digit 8).

Mnemonic: group.

Examples:

/(\w+) \g1/;    # Finds a duplicated word, (e.g. "cat cat").
/(\w+) \1/;     # Same thing; written old-style.
/(\w+) \g{1}/;  # Same, using the safer braced notation
/(\w+) \g{ 1 }/;# Same, showing optional blanks adjacent to the braces
/(.)(.)\g2\g1/; # Match a four letter palindrome (e.g. "ABBA").

πŸ¦‹ Relative referencing πŸ¦‹

\g-N (starting in Perl 5.10.0) is used for relative addressing. (It can be written as \g{-N}.) It refers to the Nth group before the \g{-N}. (Blanks are allowed next to the braces too.)

The big glow-up here is that it makes it so much easier to write patterns with references that can be interpolated into larger patterns β€” even if that larger pattern also contains capture groups. That's the whole point, and it's a slay.

Examples:

/(A)        # Group 1
 (          # Group 2
   (B)      # Group 3
   \g{-1}   # Refers to group 3 (B)
   \g{-3}   # Refers to group 1 (A)
   \g{ -3 } # Same, showing optional blanks adjacent to the braces
 )
/x;         # Matches "ABBA".

my $qr = qr /(.)(.)\g{-2}\g{-1}/;  # Matches 'abab', 'cdcd', etc.
/$qr$qr/                           # Matches 'ababcdcd'.

πŸŽ€ Named referencing πŸŽ€

So \g{name} (that's from Perl 5.10.0, bestie, it's been around) lets you back refer to a named capture group β€” meaning you get to completely stop thinking about capture buffer positions entirely. Positions who? Never heard of her. πŸ’…

And because .Net regexes are also out here living their life, \g{name} can also be written as \k{name}, \k<name> or \k'name'. Same energy, different outfit. ✨

To prevent any ambiguity, name must not start with a digit nor contain a hyphen. No cap, that's just the rule.

Examples

 /(?<word>\w+) \g{word}/   # Finds duplicated word, (e.g. "cat cat")
 /(?<word>\w+) \k{word}/   # Same.
 /(?<word>\w+) \g{ word }/ # Same, showing optional blanks adjacent to
                           # the braces
 /(?<word>\w+) \k{ word }/ # Same.
 /(?<word>\w+) \k<word>/   # Same.  There are no braces, so no blanks
                           # are permitted
 /(?<letter1>.)(?<letter2>.)\g{letter2}\g{letter1}/
                           # Match a four letter palindrome (e.g.
                           # "ABBA")

🌸 Assertions 🌸

Okay so assertions are conditions that have to be true β€” they do NOT actually match any part of the substring. They're the vibe check, not the outfit. There are six assertions written as backslash sequences. Let's go. 🫢

  • \A β€” \A only matches at the beginning of the string. If the /m modifier isn't used, then /\A/ is equivalent to /^/. BUT β€” plot twist β€” if the /m modifier is used, then /^/ matches internal newlines, while the meaning of /\A/ is not changed by /m. \A matches at the beginning of the string regardless of whether /m is used. Iconic, unaffected, unbothered. πŸ‘‘
  • \z, \Z β€” \z and \Z match at the end of the string. If the /m modifier isn't used, then /\Z/ is equivalent to /$/; that is, it matches at the end of the string, or one before the newline at the end of the string. If /m is used, then /$/ matches at internal newlines, but the meaning of /\Z/ isn't changed by /m. \Z matches at the end of the string (or just before a trailing newline) regardless of whether /m is used.

\z is just like \Z, except that it does not match before a trailing newline. \z matches at the end of the string only, regardless of the modifiers used, and not just before a newline. It's the way to anchor your match to the ~true~ end of the string under all conditions. Fr fr, if you need the actual end, \z is your girl. πŸ’–

  • \G β€” \G is usually used only in combination with the /g modifier. If /g is used and the match is done in scalar context, Perl remembers where in the source string the last match ended, and the next time it starts the match from where it ended previously.

\G matches the point where the previous match on that string ended, or the beginning of that string if there was no previous match.

Mnemonic: Global. 🌈

  • \b{}, \b, \B{}, \B β€” okay this one's a whole family, stay with me bestie:

\b{...}, available starting in v5.22, matches a boundary (between two characters, or before the first character of the string, or after the final character of the string) based on the Unicode rules for the boundary type specified inside the braces. The boundary types are given a few paragraphs below. \B{...} matches at any place between characters where \b{...} of the same type doesn't match.

\b, when not immediately followed by a {, is available in all Perls. It matches at any place between a word (something matched by \w) and a non-word character (\W); \B, when not immediately followed by a {, matches at any place between characters where \b doesn't match. To get better word matching of natural language text, see \b{wb} below.

\b and \B assume there's a non-word character before the beginning and after the end of the source string; so \b will match at the beginning (or end) of the source string if the source string begins (or ends) with a word character. Otherwise, \B will match.

Do not use something like \b=head\d\b and expect it to match the beginning of a line. It literally can't, because for there to be a boundary before the non-word =, there must be a word character immediately previous. All plain \b and \B boundary determinations look for word characters alone β€” not for non-word characters, not for string ends.

It may help to understand how \b and \B work by equating them like this:

    \b  really means    (?:(?<=\w)(?!\w)|(?<!\w)(?=\w))
    \B  really means    (?:(?<=\w)(?=\w)|(?<!\w)(?!\w))

In contrast, \b{...} and \B{...} may or may not match at the beginning and end of the line, depending on the boundary type. These implement the Unicode default boundaries, specified in <https://www.unicode.org/reports/tr14/> and <https://www.unicode.org/reports/tr29/>. The boundary types are:

\b{gcb} or \b{g}

This matches a Unicode "Grapheme Cluster Boundary". (Actually Perl always uses the improved "extended" grapheme cluster".) These are explained below under \X. In fact, \X is another way to get the same functionality. It is equivalent to /.+?\b{gcb}/. Use whichever is most convenient for your situation. ✨

\b{lb}

This matches according to the default Unicode Line Breaking Algorithm (<https://www.unicode.org/reports/tr14/>), as customized in that document (Example 7 of revision 35 <https://www.unicode.org/reports/tr14/tr14-35.html#Example7>) for better handling of numeric expressions.

This is suitable for many purposes, but the Unicode::LineBreak module is available on CPAN that provides many more features, including customization. πŸŽ€

\b{sb}

This matches a Unicode "Sentence Boundary". This is an aid to parsing natural language sentences. It gives good, but imperfect results. For example, it thinks that "Mr. Smith" is two sentences. More details are at <https://www.unicode.org/reports/tr29/>. Note also that it thinks that anything matching \R (except form feed and vertical tab) is a sentence boundary. \b{sb} works with text designed for word-processors which wrap lines automatically for display, but hard-coded line boundaries are considered to be essentially the ends of text blocks (paragraphs really), and hence the ends of sentences. \b{sb} doesn't do well with text containing embedded newlines, like the source text of the document you are reading. Such text needs to be preprocessed to get rid of the line separators before looking for sentence boundaries. Some people view this as a bug in the Unicode standard, and this behavior is quite subject to change in future Perl versions. 😭

\b{wb}

This matches a Unicode "Word Boundary", but tailored to Perl expectations. This gives better (though not perfect) results for natural language processing than plain \b (without braces) does. For example, it understands that apostrophes can be in the middle of words and that parentheses aren't (see the examples below). More details are at <https://www.unicode.org/reports/tr29/>.

The current Unicode definition of a Word Boundary matches between every white space character. Perl tailors this, starting in version 5.24, to generally not break up spans of white space, just as plain \b has always functioned. This allows \b{wb} to be a drop-in replacement for \b, but with generally better results for natural language processing. (The exception to this tailoring is when a span of white space is immediately followed by something like U+0303, COMBINING TILDE. If the final space character in the span is a horizontal white space, it is broken out so that it attaches instead to the combining character. To be precise, if a span of white space that ends in a horizontal space has the character immediately following it have any of the Word Boundary property values "Extend", "Format" or "ZWJ", the boundary between the final horizontal space character and the rest of the span matches \b{wb}. In all other cases the boundary between two white space characters matches \B{wb}.)


⚠️ It is important to realize when you use these Unicode boundaries, that you are taking a risk that a future version of Perl which contains a later version of the Unicode Standard will not work precisely the same way as it did when your code was written. These rules are not considered stable and have been somewhat more subject to change than the rest of the Standard. Unicode reserves the right to change them at will, and Perl reserves the right to update its implementation to Unicode's new rules. In the past, some changes have been because new characters have been added to the Standard which have different characteristics than all previous characters, so new rules are formulated for handling them. These should not cause any backward compatibility issues. But some changes have changed the treatment of existing characters because the Unicode Technical Committee has decided that the change is warranted for whatever reason. This could be to fix a bug, or because they think better results are obtained with the new rule.
⚠️ It is also important to realize that these are default boundary definitions, and that implementations may wish to tailor the results for particular purposes and locales. For example, some languages, such as Japanese and Thai, require dictionary lookup to accurately determine word boundaries.

Mnemonic: boundary. πŸ¦‹

Examples

 "cat"   =~ /\Acat/;     # Match.
 "cat"   =~ /cat\Z/;     # Match.
 "cat\n" =~ /cat\Z/;     # Match.
 "cat\n" =~ /cat\z/;     # No match.

 "cat"   =~ /\bcat\b/;   # Matches.
 "cats"  =~ /\bcat\b/;   # No match.
 "cat"   =~ /\bcat\B/;   # No match.
 "cats"  =~ /\bcat\B/;   # Match.

 while ("cat dog" =~ /(\w+)/g) {
     print $1;           # Prints 'catdog'
 }
 while ("cat dog" =~ /\G(\w+)/g) {
     print $1;           # Prints 'cat'
 }

 my $s = "He said, \"Is pi 3.14? (I'm not sure).\"";
 print join("|", $s =~ m/ ( .+? \b     ) /xg), "\n";
 print join("|", $s =~ m/ ( .+? \b{wb} ) /xg), "\n";
prints
 He| |said|, "|Is| |pi| |3|.|14|? (|I|'|m| |not| |sure
 He| |said|,| |"|Is| |pi| |3.14|?| |(|I'm| |not| |sure|)|.|"

Look at that second line eat. πŸ’… \b{wb} understood that 3.14 is one thing and that I'm is one thing. That's the whole point, bestie. πŸ“


πŸŽ€ Misc πŸŽ€

Here we document the backslash sequences that don't fall in one of the categories above. These are:

🌟 \K β€” the "keep it to yourself" girlie

This appeared in perl 5.10.0. Anything matched left of \K is not included in $&, and will not be replaced if the pattern is used in a substitution. So instead of doing the whole messy capture-group dance, you can just write s/PAT1 \K PAT2/REPL/x instead of s/(PAT1) PAT2/${1}REPL/x or s/(?<=PAT1) PAT2/REPL/x. Literally so much cleaner, bestie. ✨

Mnemonic: Keep. πŸ’…


🌈 \N β€” not-a-newline, thanks

This feature, available starting in v5.12, matches any character that is not a newline. It's a short-hand for writing [^\n], and is identical to the . metasymbol, except under the /s flag, which changes the meaning of ., but not \N. πŸ¦‹

Note that \N{...} can mean a named or numbered character . πŸ‘€

Mnemonic: Complement of \n. πŸŽ€


πŸ”₯ \R β€” the generic newline, no cap

\R matches a generic newline; that is, anything considered a linebreak sequence by Unicode. This includes all characters matched by \v (vertical whitespace), and the multi character sequence \x0D\x0A (carriage return followed by a line feed, sometimes called the network newline; it's the end of line sequence used in Microsoft text files opened in binary mode). \R is equivalent to (?>\x0D\x0A|\v). (The reason it doesn't backtrack is that the sequence is considered inseparable. That means that

"\x0D\x0A" =~ /^\R\x0A$/   # No match

fails, because the \R matches the entire string, and won't backtrack to match just the \x0D. πŸ™ˆ)

Since \R can match a sequence of more than one character, it cannot be put inside a bracketed character class; /[\R]/ is an error; use \v instead. πŸ“£

\R was introduced in perl 5.10.0. (vintage icon behavior, honestly)

Note that this does not respect any locale that might be in effect; it matches according to the platform's native character set. 🫢

Mnemonic: none really. \R was picked because PCRE already uses \R, and more importantly because Unicode recommends such a regular expression metacharacter, and suggests \R as its notation. πŸ’œ


πŸ‘‘ \X β€” the grapheme cluster queen

This matches a Unicode extended grapheme cluster. πŸ’«

\X matches quite well what normal (non-Unicode-programmer) usage would consider a single character. As an example, consider a G with some sort of diacritic mark, such as an arrow. There is no such single character in Unicode, but one can be composed by using a G followed by a Unicode "COMBINING UPWARDS ARROW BELOW", and would be displayed by Unicode-aware software as if it were a single character. it's giving "one character, but make it a collab" πŸ“

The match is greedy and non-backtracking, so that the cluster is never broken up into smaller components. 🧚

See also \b{gcb}. πŸŽ€

Mnemonic: eXtended Unicode character. ⭐


✨ Examples ✨

Okay bestie, here's the receipts β€” run 'em and see for yourself πŸ”₯

 $str =~ s/foo\Kbar/baz/g; # Change any 'bar' following a 'foo' to 'baz'
 $str =~ s/(.)\K\g1//g;    # Delete duplicated characters.

 "\n"   =~ /^\R$/;         # Match, \n   is a generic newline.
 "\r"   =~ /^\R$/;         # Match, \r   is a generic newline.
 "\r\n" =~ /^\R$/;         # Match, \r\n is a generic newline.

 "P\x{307}" =~ /^\X$/     # \X matches a P with a dot above.

And that's the whole page, bestie!! 🫢 You just read the perl v5.44.0 edition of PERLREBACKSLASH(1perl), dated 2026-10-17, and honestly you absolutely ate. πŸ’…βœ¨ Go write some regexes, you main character. πŸ’–πŸŽ€πŸ¦‹

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms