Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Tools

perlreref

Perl 5 version 10.1 documentation
Recently read

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/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().

SYNTAX

  1. \ Escapes the character immediately following it
  2. . Matches any single character except a newline (unless /s is used)
  3. ^ Matches at the beginning of the string (or line, if /m is used)
  4. $ Matches at the end of the string (or line, if /m is used)
  5. * Matches the preceding element 0 or more times
  6. + Matches the preceding element 1 or more times
  7. ? Matches the preceding element 0 or 1 times
  8. {...} Specifies a range of occurrences for the element preceding it
  9. [...] Matches any one of the characters contained within the brackets
  10. (...) Groups subexpressions for capturing to $1, $2...
  11. (?:...) Groups subexpressions without capturing (cluster)
  12. | Matches either the subexpression preceding or following it
  13. \1, \2, \3 ... Matches the text from the Nth group
  14. \g1 or \g{1}, \g2 ... Matches the text from the Nth group
  15. \g-1 or \g{-1}, \g-2 ... Matches the text from the Nth previous group
  16. \g{name} Named backreference
  17. \k<name> Named backreference
  18. \k'name' Named backreference
  19. (?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 Any octal ASCII value
  8. \x7f Any hexadecimal ASCII value
  9. \x{263a} A wide hexadecimal value
  10. \cx Control-x
  11. \N{name} A named character
  12. \l Lowercase next character
  13. \u Titlecase next character
  14. \L Lowercase until \E
  15. \U Uppercase until \E
  16. \Q Disable pattern metacharacters until \E
  17. \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 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 white space
  8. \H A non horizontal white space
  9. \v A vertical white space
  10. \V A non vertical white space
  11. \R A generic newline (?>\v|\x0D\x0A)
  12. \C Match a byte (with Unicode, '.' matches a character)
  13. \pP Match P-named (Unicode) property
  14. \p{...} Match Unicode property with long name
  15. \PP Match non-P
  16. \P{...} Match lack of Unicode property with long name
  17. \X Match extended Unicode combining character sequence

POSIX character classes and their Unicode and Perl equivalents:

  1. alnum IsAlnum Alphanumeric
  2. alpha IsAlpha Alphabetic
  3. ascii IsASCII Any ASCII char
  4. blank IsSpace [ \t] Horizontal whitespace (GNU extension)
  5. cntrl IsCntrl Control characters
  6. digit IsDigit \d Digits
  7. graph IsGraph Alphanumeric and punctuation
  8. lower IsLower Lowercase chars (locale and Unicode aware)
  9. print IsPrint Alphanumeric, punct, and space
  10. punct IsPunct Punctuation
  11. space IsSpace [\s\ck] Whitespace
  12. IsSpacePerl \s Perl's whitespace definition
  13. upper IsUpper Uppercase chars (locale and Unicode aware)
  14. word IsWord \w Alphanumeric plus _ (Perl extension)
  15. xdigit IsXDigit [0-9A-Fa-f] Hexadecimal digit

Within a character class:

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

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 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

Quantifiers are greedy by default -- 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 gets understood 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. (?{ 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

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

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.

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. 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.

TERMINOLOGY

Titlecase

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

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.