• TUX



Perl 5 version 12.5 documentation
Recently read



perlreref - Perl Regular Expressions Reference


This is a quick reference to Perl's regular expressions. For full information see perlre and perlop, as well as the SEE ALSO section in this document.


=~ determines to which variable the regex is applied. In its absence, $_ is used.

  1. $var =~ /foo/;

!~ determines to which variable the regex is applied, and negates the result of the match; it returns false if the match succeeds, and true if it fails.

  1. $var !~ /foo/;

m/pattern/msixpogc searches a string for a pattern match, applying the given options.

  1. m Multiline mode - ^ and $ match internal lines
  2. s match as a Single line - . matches \n
  3. i case-Insensitive
  4. x eXtended legibility - free whitespace and comments
  5. p Preserve a copy of the matched string -
  6. ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
  7. o compile pattern Once
  8. g Global - all occurrences
  9. c don't reset pos on failed matches when using /g

If 'pattern' is an empty string, the last successfully matched regex is used. Delimiters other than '/' may be used for both this operator and the following ones. The leading m can be omitted if the delimiter is '/'.

qr/pattern/msixpo lets you store a regex in a variable, or pass one around. Modifiers as for m//, and are stored within the regex.

s/pattern/replacement/msixpogce substitutes matches of 'pattern' with 'replacement'. Modifiers as for m//, with one addition:

  1. e Evaluate 'replacement' as an expression

'e' may be specified multiple times. 'replacement' is interpreted as a double quoted string unless a single-quote (') is the delimiter.

?pattern? is like m/pattern/ but matches only once. No alternate delimiters can be used. Must be reset with reset().


  1. \ Escapes the character immediately following it
  2. . Matches any single character except a newline (unless /s is
  3. used)
  4. ^ Matches at the beginning of the string (or line, if /m is used)
  5. $ Matches at the end of the string (or line, if /m is used)
  6. * Matches the preceding element 0 or more times
  7. + Matches the preceding element 1 or more times
  8. ? Matches the preceding element 0 or 1 times
  9. {...} Specifies a range of occurrences for the element preceding it
  10. [...] Matches any one of the characters contained within the brackets
  11. (...) Groups subexpressions for capturing to $1, $2...
  12. (?:...) Groups subexpressions without capturing (cluster)
  13. | Matches either the subexpression preceding or following it
  14. \1, \2, \3 ... Matches the text from the Nth group
  15. \g1 or \g{1}, \g2 ... Matches the text from the Nth group
  16. \g-1 or \g{-1}, \g-2 ... Matches the text from the Nth previous group
  17. \g{name} Named backreference
  18. \k<name> Named backreference
  19. \k'name' Named backreference
  20. (?P=name) Named backreference (python syntax)


These work as in normal strings.

  1. \a Alarm (beep)
  2. \e Escape
  3. \f Formfeed
  4. \n Newline
  5. \r Carriage return
  6. \t Tab
  7. \037 Char whose ordinal is the 3 octal digits, max \777
  8. \o{2307} Char whose ordinal is the octal number, unrestricted
  9. \x7f Char whose ordinal is the 2 hex digits, max \xFF
  10. \x{263a} Char whose ordinal is the hex number, unrestricted
  11. \cx Control-x
  12. \N{name} A named Unicode character
  13. \N{U+263D} A Unicode character by hex ordinal
  14. \l Lowercase next character
  15. \u Titlecase next character
  16. \L Lowercase until \E
  17. \U Uppercase until \E
  18. \Q Disable pattern metacharacters until \E
  19. \E End modification

For Titlecase, see Titlecase.

This one works differently from normal strings:

  1. \b An assertion, not backspace, except in a character class


  1. [amy] Match 'a', 'm' or 'y'
  2. [f-j] Dash specifies "range"
  3. [f-j-] Dash escaped or at start or end means 'dash'
  4. [^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, all are Unicode aware. See perllocale and perlunicode for details.

  1. \d A digit
  2. \D A nondigit
  3. \w A word character
  4. \W A non-word character
  5. \s A whitespace character
  6. \S A non-whitespace character
  7. \h An horizontal whitespace
  8. \H A non horizontal whitespace
  9. \N A non newline (when not followed by '{NAME}'; experimental;
  10. not valid in a character class; equivalent to [^\n]; it's
  11. like '.' without /s modifier)
  12. \v A vertical whitespace
  13. \V A non vertical whitespace
  14. \R A generic newline (?>\v|\x0D\x0A)
  15. \C Match a byte (with Unicode, '.' matches a character)
  16. \pP Match P-named (Unicode) property
  17. \p{...} Match Unicode property with name longer than 1 character
  18. \PP Match non-P
  19. \P{...} Match lack of Unicode property with name longer than 1 char
  20. \X Match Unicode extended grapheme cluster

POSIX character classes and their Unicode and Perl equivalents:

  1. ASCII- Full-
  2. range range backslash
  3. POSIX \p{...} \p{} sequence Description
  4. -----------------------------------------------------------------------
  5. alnum PosixAlnum Alnum Alpha plus Digit
  6. alpha PosixAlpha Alpha Alphabetic characters
  7. ascii ASCII Any ASCII character
  8. blank PosixBlank Blank \h Horizontal whitespace;
  9. full-range also written
  10. as \p{HorizSpace} (GNU
  11. extension)
  12. cntrl PosixCntrl Cntrl Control characters
  13. digit PosixDigit Digit \d Decimal digits
  14. graph PosixGraph Graph Alnum plus Punct
  15. lower PosixLower Lower Lowercase characters
  16. print PosixPrint Print Graph plus Print, but not
  17. any Cntrls
  18. punct PosixPunct Punct These aren't precisely
  19. equivalent. See NOTE,
  20. below.
  21. space PosixSpace Space [\s\cK] Whitespace
  22. PerlSpace SpacePerl \s Perl's whitespace
  23. definition
  24. upper PosixUpper Upper Uppercase characters
  25. word PerlWord Word \w Alnum plus '_' (Perl
  26. extension)
  27. xdigit ASCII_Hex_Digit XDigit Hexadecimal digit,
  28. ASCII-range is
  29. [0-9A-Fa-f]

NOTE on [[:punct:]], \p{PosixPunct} and \p{Punct} : In the ASCII range, [[:punct:]] and \p{PosixPunct} match [-!"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~] (although if a locale is in effect, it could alter the behavior of [[:punct:]]); and \p{Punct} matches [-!"#%&'()*,./:;?@[\\\]_{}] . When matching a UTF-8 string, [[:punct:]] matches what it does in the ASCII range, plus what \p{Punct} matches. \p{Punct} matches, anything that isn't a control, an alphanumeric, a space, nor a symbol.

Within a character class:

  1. POSIX traditional Unicode
  2. [:digit:] \d \p{Digit}
  3. [:^digit:] \D \P{Digit}


All are zero-width assertions.

  1. ^ Match string start (or line, if /m is used)
  2. $ Match string end (or line, if /m is used) or before newline
  3. \b Match word boundary (between \w and \W)
  4. \B Match except at word boundary (between \w and \w or \W and \W)
  5. \A Match string start (regardless of /m)
  6. \Z Match string end (before optional newline)
  7. \z Match absolute string end
  8. \G Match where previous m//g left off
  9. \K Keep the stuff left of the \K, don't include it in $&


Quantifiers are greedy by default and match the longest leftmost.

  1. Maximal Minimal Possessive Allowed range
  2. ------- ------- ---------- -------------
  3. {n,m} {n,m}? {n,m}+ Must occur at least n times
  4. but no more than m times
  5. {n,} {n,}? {n,}+ Must occur at least n times
  6. {n} {n}? {n}+ Must occur exactly n times
  7. * *? *+ 0 or more times (same as {0,})
  8. + +? ++ 1 or more times (same as {1,})
  9. ? ?? ?+ 0 or 1 time (same as {0,1})

The possessive forms (new in Perl 5.10) 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.

There is no quantifier {,n} . That's interpreted as a literal string.


  1. (?#text) A comment
  2. (?:...) Groups subexpressions without capturing (cluster)
  3. (?pimsx-imsx:...) Enable/disable option (as per m// modifiers)
  4. (?=...) Zero-width positive lookahead assertion
  5. (?!...) Zero-width negative lookahead assertion
  6. (?<=...) Zero-width positive lookbehind assertion
  7. (?<!...) Zero-width negative lookbehind assertion
  8. (?>...) Grab what we can, prohibit backtracking
  9. (?|...) Branch reset
  10. (?<name>...) Named capture
  11. (?'name'...) Named capture
  12. (?P<name>...) Named capture (python syntax)
  13. (?{ code }) Embedded code, return value becomes $^R
  14. (??{ code }) Dynamic regex, return value used as regex
  15. (?N) Recurse into subpattern number N
  16. (?-N), (?+N) Recurse into Nth previous/next subpattern
  17. (?R), (?0) Recurse at the beginning of the whole pattern
  18. (?&name) Recurse into a named subpattern
  19. (?P>name) Recurse into a named subpattern (python syntax)
  20. (?(cond)yes|no)
  21. (?(cond)yes) Conditional expression, where "cond" can be:
  22. (N) subpattern N has matched something
  23. (<name>) named subpattern has matched something
  24. ('name') named subpattern has matched something
  25. (?{code}) code condition
  26. (R) true if recursing
  27. (RN) true if recursing into Nth subpattern
  28. (R&name) true if recursing into named subpattern
  29. (DEFINE) always false, no no-pattern allowed


  1. $_ Default variable for operators to use
  2. $` Everything prior to matched string
  3. $& Entire matched string
  4. $' Everything after to matched string
  5. ${^PREMATCH} Everything prior to matched string
  6. ${^MATCH} Entire matched string
  7. ${^POSTMATCH} Everything after to matched string

The use of $` , $& or $' will slow down all regex use within your program. Consult perlvar for @- to see equivalent expressions that won't cause slow down. See also Devel::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.

  1. $1, $2 ... hold the Xth captured expr
  2. $+ Last parenthesized pattern match
  3. $^N Holds the most recently closed capture
  4. $^R Holds the result of the last (?{...}) expr
  5. @- Offsets of starts of groups. $-[0] holds start of whole match
  6. @+ Offsets of ends of groups. $+[0] holds end of whole match
  7. %+ Named capture buffers
  8. %- Named capture buffers, as array refs

Captured groups are numbered according to their opening paren.


  1. lc Lowercase a string
  2. lcfirst Lowercase first char of a string
  3. uc Uppercase a string
  4. ucfirst Titlecase first char of a string
  5. pos Return or set current match position
  6. quotemeta Quote metacharacters
  7. reset Reset ?pattern? status
  8. study Analyze string for optimizing matching
  9. split Use a regex to split a string into parts

The first four of these are like the escape sequences \L , \l , \U , and \u . For Titlecase, see Titlecase.



Unicode concept which most often is equal to uppercase, but for certain characters like the German "sharp s" there is a difference.


Iain Truskett. Updated by the Perl 5 Porters.

This document may be distributed under the same terms as Perl itself.



David P.C. Wollmann, Richard Soderberg, Sean M. Burke, Tom Christiansen, Jim Cromie, and Jeffrey Goff for useful advice.