PERLREREF(1perl)
πΈ NAME πΈ
perlreref β the Perl Regular Expressions Reference, sitting pretty in section 1perl of the manual pages. She's not a tutorial bestie, she's a cheat sheet, and she is iconic for it. π
β¨ DESCRIPTION β¨
okay so this is your quick reference to Perl's regular expressions. That's it, that's the job. π
If you want the full story β the deep lore, the extended cut, the director's commentary β go read perlre and perlop, plus the SEE ALSO section down at the bottom of this very document. No cap. π
π OPERATORS π
So you gotta know which variable you're matching against, and that's what these bad boys are for.
=~β this one decides which variable the regex gets applied to. And if you just... don't use it? Then$_gets volunteered for the job. no thoughts, head empty,$_it is. π«Ά
$var =~ /foo/;
!~β same deal, it picks which variable the regex applies to, but it negates the result of the match. Translation: it returns false if the match succeeds, and true if it fails. chaotic, but she's right. π
$var !~ /foo/;
π¦ The match operators
m/pattern/msixpogcdualnβ searches a string for a pattern match, applying whatever options you handed it. Here's the whole menu of modifiers:mβ Multiline mode β^and$match internal linessβ match as a Single line β.matches\niβ case-Insensitivexβ eXtended legibility β free whitespace and commentspβ Preserve a copy of the matched string β${^PREMATCH},${^MATCH},${^POSTMATCH}will be defined.oβ compile pattern Oncegβ Global β all occurrencescβ don't resetposon failed matches when using/gaβ restrict\d,\s,\wand[:posix:]to match ASCII onlyaaβ (two a's) also/imatches exclude ASCII/non-ASCIIlβ match according to current localeuβ match according to Unicode rulesdβ match according to native rules unless something indicates Unicodenβ Non-capture mode. Don't let()fill in$1,$2, etc...
If 'pattern' is an empty string, the last successfully matched regex is used. (she remembers. π) Delimiters other than / may be used for both this operator and the following ones. And the leading m can be omitted if the delimiter is /.
qr/pattern/msixpodualnβ this one lets you store a regex in a variable, or pass one around like a lil friendship bracelet. Modifiers are as form//, and they get stored within the regex. πs/pattern/replacement/msixpogcedualβ substitutes matches of 'pattern' with 'replacement'. Modifiers as form//, with two extra additions:eβ Evaluate 'replacement' as an expressionrβ Return substitution and leave the original string untouched.
emay be specified multiple times. And heads up: 'replacement' is interpreted as a double quoted string unless a single-quote (') is the delimiter. π
m?pattern?β it's likem/pattern/but it matches only once. No alternate delimiters can be used. Must be reset withreset(). one chance only, bestie. π₯²
πΈ SYNTAX πΈ
The whole alphabet of regex building blocks, right here:
\β Escapes the character immediately following it.β Matches any single character except a newline (unless/sis used)^β Matches at the beginning of the string (or line, if/mis used)$β Matches at the end of the string (or line, if/mis used)*β Matches the preceding element 0 or more times+β Matches the preceding element 1 or more times?β Matches the preceding element 0 or 1 times{...}β Specifies a range of occurrences for the element preceding it[...]β Matches any one of the characters contained within the brackets(...)β Groups subexpressions for capturing to$1,$2...(?:...)β Groups subexpressions without capturing (cluster)|β Matches either the subexpression preceding or following it\g1or\g{1},\g2... β Matches the text from the Nth group\1,\2,\3... β Matches the text from the Nth group\g-1or\g{-1},\g-2... β Matches the text from the Nth previous group\g{name}β Named backreference\k<name>β Named backreference\k'name'β Named backreference(?P=name)β Named backreference (python syntax)
π ESCAPE SEQUENCES π
These work as in normal strings. fr fr. π
\aβ Alert (beep)\eβ Escape\fβ Formfeed\nβ Newline\rβ Carriage return\tβ Tab\037β Char whose ordinal is the 3 octal digits, max\777\o{2307}β Char whose ordinal is the octal number, unrestricted\x7fβ Char whose ordinal is the 2 hex digits, max\xFF\x{263a}β Char whose ordinal is the hex number, unrestricted\cxβ Control-x\N{name}β A named Unicode character or character sequence\N{U+263D}β A Unicode character by hex ordinal
And the case-flipping squad:
\lβ Lowercase next character\uβ Titlecase next character\Lβ Lowercase until\E\Uβ Uppercase until\E\Fβ Foldcase until\E\Qβ Disable pattern metacharacters until\E\Eβ End modification
For Titlecase, see "Titlecase". π
And then this ONE little gremlin works differently from normal strings:
\bβ An assertion, not backspace, except in a character class
Not backspace!! bestie I'm serious, this trips people up constantly. it is an assertion. an anchor. not a delete key. π
π CHARACTER CLASSES π
[amy]β Match 'a', 'm' or 'y'[f-j]β Dash specifies "range"[f-j-]β Dash escaped or at start or end means 'dash'[^f-j]β Caret indicates "match any character _except_ these"
The following sequences (except \N) work within or without a character class. The first six are locale aware, and all are Unicode aware. See perllocale and perlunicode for details. π
\dβ A digit\Dβ A nondigit\wβ A word character\Wβ A non-word character\sβ A whitespace character\Sβ A non-whitespace character\hβ A horizontal whitespace\Hβ A non horizontal whitespace\Nβ A non newline (when not followed by '{NAME}';; not valid in a character class; equivalent to[^\n]; it's like '.' without/smodifier)\vβ A vertical whitespace\Vβ A non vertical whitespace\Rβ A generic newline(?>\x0D\x0A|\v)\pPβ Match P-named (Unicode) property\p{...}β Match Unicode property with name longer than 1 character\PPβ Match non-P\P{...}β Match lack of Unicode property with name longer than 1 char\Xβ Match Unicode extended grapheme cluster
π¦ POSIX character classes and their Unicode and Perl equivalents
the glow up is real, look at this list:
[[:alnum:]]β ASCII-range\p{PosixAlnum}, full-range\p{XPosixAlnum}β 'alpha' plus 'digit'[[:alpha:]]β ASCII-range\p{PosixAlpha}, full-range\p{XPosixAlpha}β Alphabetic characters[[:ascii:]]β ASCII-range\p{ASCII}β Any ASCII character[[:blank:]]β ASCII-range\p{PosixBlank}, full-range\p{XPosixBlank}, backslash sequence\hβ Horizontal whitespace; full-range also written as\p{HorizSpace}[[:cntrl:]]β ASCII-range\p{PosixCntrl}, full-range\p{XPosixCntrl}β Control characters[[:digit:]]β ASCII-range\p{PosixDigit}, full-range\p{XPosixDigit}, backslash sequence\dβ Decimal digits[[:graph:]]β ASCII-range\p{PosixGraph}, full-range\p{XPosixGraph}β 'alnum' plus 'punct'[[:lower:]]β ASCII-range\p{PosixLower}, full-range\p{XPosixLower}β Lowercase characters[[:print:]]β ASCII-range\p{PosixPrint}, full-range\p{XPosixPrint}β 'graph' plus 'space', but not any Controls[[:punct:]]β ASCII-range\p{PosixPunct}, full-range\p{XPosixPunct}β Punctuation and Symbols in ASCII-range; just punct outside it[[:space:]]β ASCII-range\p{PosixSpace}, full-range\p{XPosixSpace}, backslash sequence\sβ Whitespace[[:upper:]]β ASCII-range\p{PosixUpper}, full-range\p{XPosixUpper}β Uppercase characters[[:word:]]β ASCII-range\p{PosixWord}, full-range\p{XPosixWord}, backslash sequence\wβ 'alnum' + Unicode marks + connectors, like '_' (Perl extension)[[:xdigit:]]β ASCII-range\p{ASCII_Hex_Digit}, full-range\p{XPosixDigit}β Hexadecimal digit, ASCII-range is[0-9A-Fa-f]
Also, various synonyms like \p{Alpha} for \p{XPosixAlpha}; all listed in "Properties accessible through \p{} and \P{}" in perluniprops. π
Within a character class:
- POSIX
[:digit:], traditional\d, Unicode\p{Digit} - POSIX
[:^digit:], traditional\D, Unicode\P{Digit}
β ANCHORS β
All of these are zero-width assertions. They match a position, not a character. slay. π
^β Match string start (or line, if/mis used)$β Match string end (or line, if/mis used) or before newline\b{}β Match boundary of type specified within the braces\B{}β Match wherever\b{}doesn't match\bβ Match word boundary (between\wand\W)\Bβ Match except at word boundary (between\wand\wor\Wand\W)\Aβ Match string start (regardless of/m)\Zβ Match string end (before optional newline)\zβ Match absolute string end\Gβ Match where previousm//gleft off\Kβ Keep the stuff left of the\K, don't include it in$&
π₯ QUANTIFIERS π₯
Quantifiers are greedy by default and match the longest leftmost. she takes what she can get. π
For each row below: Maximal, Minimal, Possessive, then the allowed range.
{n,m}β{n,m}?β{n,m}+β Must occur at least n times but no more than m times{n,}β{n,}?β{n,}+β Must occur at least n times{,n}β{,n}?β{,n}+β Must occur at most n times{n}β{n}?β{n}+β Must occur exactly n times*β*?β*+β 0 or more times (same as{0,})+β+?β++β 1 or more times (same as{1,})?β??β?+β 0 or 1 time (same as{0,1})
The possessive forms (new in Perl 5.10, so she's a lil vintage icon π) prevent backtracking: what gets matched by a pattern with a possessive quantifier will not be backtracked into, even if that causes the whole match to fail.
like... she said what she said and she is NOT reconsidering. π periodt.
β¨ EXTENDED CONSTRUCTS β¨
okay bestie, these are the β¨fancyβ¨ regex moves, and you're gonna eat them up π
(?#text)β A comment. literally just a little note in ur pattern, ignore me π¬(?:...)β Groups subexpressions without capturing (cluster). the way it groups but doesn't keep receipts β¨(?pimsx-imsx:...)β Enable/disable option (as perm//modifiers)(?=...)β Zero-width positive lookahead assertion(*pla:...)β Same, starting in 5.32; experimentally in 5.28(*positive_lookahead:...)β Same, same versions as*pla(?!...)β Zero-width negative lookahead assertion(*nla:...)β Same, starting in 5.32; experimentally in 5.28(*negative_lookahead:...)β Same, same versions as*nla(?<=...)β Zero-width positive lookbehind assertion(*plb:...)β Same, starting in 5.32; experimentally in 5.28(*positive_lookbehind:...)β Same, same versions as*plb(?<!...)β Zero-width negative lookbehind assertion(*nlb:...)β Same, starting in 5.32; experimentally in 5.28(*negative_lookbehind:...)β Same, same versions as*plb(yes bestie, it says*plb, not*nlb, keep it exactly like that)(?>...)β Grab what we can, prohibit backtracking(*atomic:...)β Same, starting in 5.32; experimentally in 5.28(?|...)β Branch reset(?<name>...)β Named capture(?'name'...)β Named capture(?P<name>...)β Named capture (python syntax)(?[...])β Extended bracketed character class(?{ code })β Embedded code, return value becomes$^R(??{ code })β Dynamic regex, return value used as regex(?N)β Recurse into subpattern number N(?-N), (?+N)β Recurse into Nth previous/next subpattern(?R), (?0)β Recurse at the beginning of the whole pattern(?&name)β Recurse into a named subpattern(?P>name)β Recurse into a named subpattern (python syntax)(?(cond)yes|no)(?(cond)yes)β Conditional expression, where(cond)can be:(?=pat)β lookahead; also(*pla:pat)(*positive_lookahead:pat)(?!pat)β negative lookahead; also(*nla:pat)(*negative_lookahead:pat)(?<=pat)β lookbehind; also(*plb:pat)(*lookbehind:pat)(?<!pat)β negative lookbehind; also(*nlb:pat)(*negative_lookbehind:pat)(N)β subpattern N has matched something(<name>)β named subpattern has matched something('name')β named subpattern has matched something(?{code})β code condition(R)β true if recursing(RN)β true if recursing into Nth subpattern(R&name)β true if recursing into named subpattern(DEFINE)β always false, no no-pattern allowed
π VARIABLES π
these are the little guys holding onto ur matches, bestie π₯Ί
$_β Default variable for operators to use`$`β Everything prior to matched string$&β Entire matched string$'β Everything after to matched string${^PREMATCH}β Everything prior to matched string${^MATCH}β Entire matched string${^POSTMATCH}β Everything after to matched string
π Note to those still using Perl 5.18 or earlier: The use of`$`,$&or$'will slow down all regex use within your program. Consultperlvarfor@-to see equivalent expressions that won't cause slow down. See alsoDevel::SawAmpersand. Starting with Perl 5.10, you can also use the equivalent variables${^PREMATCH},${^MATCH}and${^POSTMATCH}, but for them to be defined, you have to specify the/p(preserve) modifier on your regular expression. In Perl 5.20, the use of`$`,$&and$'makes no speed difference.
$1, $2 ...β hold the Xth captured expr$+β Last parenthesized pattern match$^Nβ Holds the most recently closed capture$^Rβ Holds the result of the last(?{...})expr@-β Offsets of starts of groups.$-[0]holds start of whole match@+β Offsets of ends of groups.$+[0]holds end of whole match%+β Named capture groups%-β Named capture groups, as array refs
Captured groups are numbered according to their opening paren. periodt π
πΈ FUNCTIONS πΈ
lcβ Lowercase a stringlcfirstβ Lowercase first char of a stringucβ Uppercase a stringucfirstβ Titlecase first char of a stringfcβ Foldcase a stringposβ Return or set current match positionquotemetaβ Quote metacharacters (escape their normal meaning)resetβ Resetm?pattern?statusstudyβ Analyze string for optimizing matchingsplitβ Use a regex to split a string into parts
The first five of these are like the escape sequences \L, \l, \U, \u, and \F. For Titlecase, see "Titlecase"; For Foldcase, see "Foldcase".
π¦ TERMINOLOGY π¦
Titlecase
Unicode concept which most often is equal to uppercase, but for certain characters like the German "sharp s" there is a difference.
Foldcase
Unicode form that is useful when comparing strings regardless of case, as certain characters have complex one-to-many case mappings. Primarily a variant of lowercase.
π AUTHOR π
Iain Truskett. Updated by the Perl 5 Porters.
This document may be distributed under the same terms as Perl itself.
π₯ SEE ALSO π₯
perlretutfor a tutorial on regular expressions.perlrequickfor a rapid tutorial.perlrefor more details.perlvarfor details on the variables.perlopfor details on the operators.perlfuncfor details on the functions.perlfaq6for FAQs on regular expressions.perlrebackslashfor a reference on backslash sequences.perlrecharclassfor a reference on character classes.- The
remodule to alter behaviour and aid debugging. - "Debugging Regular Expressions" in
perldebug perluniintro,perlunicode,charnamesandperllocalefor details on regexes and internationalisation.- Mastering Regular Expressions by Jeffrey Friedl (<https://www.oreilly.com/library/view/-/0596528124/>) for a thorough grounding and reference on the topic.
π«Ά THANKS π«Ά
David P.C. Wollmann, Richard Soderberg, Sean M. Burke, Tom Christiansen, Jim Cromie, and Jeffrey Goff for useful advice.
that's the tea, bestie π
this was perl v5.44.0, dated 2026-10-17, from PERLREREF(1perl). now go slay those regexes β¨
π¦ 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