Perl 5 version 26.3 documentation

perlreref

NAME

perlreref - Perl Regular Expressions Reference

DESCRIPTION

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.

OPERATORS

=~ 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/msixpogcdualn 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
  10. a restrict \d, \s, \w and [:posix:] to match ASCII only
  11. aa (two a's) also /i matches exclude ASCII/non-ASCII
  12. l match according to current locale
  13. u match according to Unicode rules
  14. d match according to native rules unless something indicates
  15. Unicode
  16. n Non-capture mode. Don't let () fill in $1, $2, etc...

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/msixpodualn 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/msixpogcedual substitutes matches of 'pattern' with 'replacement'. Modifiers as for m//, with two additions:

  1. e Evaluate 'replacement' as an expression
  2. r Return substitution and leave the original string untouched.

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

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

SYNTAX

  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. \g1 or \g{1}, \g2 ... Matches the text from the Nth group
  15. \1, \2, \3 ... 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)

ESCAPE SEQUENCES

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 or character sequence
  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. \F Foldcase until \E
  19. \Q Disable pattern metacharacters until \E
  20. \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

CHARACTER CLASSES

  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}';;
  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. \pP Match P-named (Unicode) property
  16. \p{...} Match Unicode property with name longer than 1 character
  17. \PP Match non-P
  18. \P{...} Match lack of Unicode property with name longer than 1 char
  19. \X Match Unicode extended grapheme cluster

POSIX character classes and their Unicode and Perl equivalents:

  1. ASCII- Full-
  2. POSIX range range backslash
  3. [[:...:]] \p{...} \p{...} sequence Description
  4. -----------------------------------------------------------------------
  5. alnum PosixAlnum XPosixAlnum 'alpha' plus 'digit'
  6. alpha PosixAlpha XPosixAlpha Alphabetic characters
  7. ascii ASCII Any ASCII character
  8. blank PosixBlank XPosixBlank \h Horizontal whitespace;
  9. full-range also
  10. written as
  11. \p{HorizSpace} (GNU
  12. extension)
  13. cntrl PosixCntrl XPosixCntrl Control characters
  14. digit PosixDigit XPosixDigit \d Decimal digits
  15. graph PosixGraph XPosixGraph 'alnum' plus 'punct'
  16. lower PosixLower XPosixLower Lowercase characters
  17. print PosixPrint XPosixPrint 'graph' plus 'space',
  18. but not any Controls
  19. punct PosixPunct XPosixPunct Punctuation and Symbols
  20. in ASCII-range; just
  21. punct outside it
  22. space PosixSpace XPosixSpace \s Whitespace
  23. upper PosixUpper XPosixUpper Uppercase characters
  24. word PosixWord XPosixWord \w 'alnum' + Unicode marks
  25. + connectors, like
  26. '_' (Perl extension)
  27. xdigit ASCII_Hex_Digit XPosixDigit Hexadecimal digit,
  28. ASCII-range is
  29. [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:

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

ANCHORS

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 boundary of type specified within the braces
  4. \B{} Match wherever \b{} doesn't match
  5. \b Match word boundary (between \w and \W)
  6. \B Match except at word boundary (between \w and \w or \W and \W)
  7. \A Match string start (regardless of /m)
  8. \Z Match string end (before optional newline)
  9. \z Match absolute string end
  10. \G Match where previous m//g left off
  11. \K Keep the stuff left of the \K, don't include it in $&

QUANTIFIERS

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.

EXTENDED CONSTRUCTS

  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. (?[...]) Extended bracketed character class
  14. (?{ code }) Embedded code, return value becomes $^R
  15. (??{ code }) Dynamic regex, return value used as regex
  16. (?N) Recurse into subpattern number N
  17. (?-N), (?+N) Recurse into Nth previous/next subpattern
  18. (?R), (?0) Recurse at the beginning of the whole pattern
  19. (?&name) Recurse into a named subpattern
  20. (?P>name) Recurse into a named subpattern (python syntax)
  21. (?(cond)yes|no)
  22. (?(cond)yes) Conditional expression, where "cond" can be:
  23. (?=pat) lookahead
  24. (?!pat) negative lookahead
  25. (?<=pat) lookbehind
  26. (?<!pat) negative lookbehind
  27. (N) subpattern N has matched something
  28. (<name>) named subpattern has matched something
  29. ('name') named subpattern has matched something
  30. (?{code}) code condition
  31. (R) true if recursing
  32. (RN) true if recursing into Nth subpattern
  33. (R&name) true if recursing into named subpattern
  34. (DEFINE) always false, no no-pattern allowed

VARIABLES

  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

Note to those still using Perl 5.18 or earlier: 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. In Perl 5.20, the use of $` , $& and $' makes no speed difference.

  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 groups
  8. %- Named capture groups, as array refs

Captured groups are numbered according to their opening paren.

FUNCTIONS

  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. fc Foldcase a string
  6. pos Return or set current match position
  7. quotemeta Quote metacharacters
  8. reset Reset m?pattern? status
  9. study Analyze string for optimizing matching
  10. split 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

THANKS

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