Regex Cheat Sheet - PCRE

A comprehensive guide to regular expressions with patterns, examples, and explanations

Basic Metacharacters

.Any character except newline
\Escape character
|Alternation (OR)
^Start of string/line
$End of string/line

Character Classes

[abc]Any of a, b, or c
[^abc]Not a, b, or c
[a-z]Range from a to z
\dDigit [0-9]
\DNon-digit [^0-9]
\wWord character [a-zA-Z0-9_]
\WNon-word character
\sWhitespace
\SNon-whitespace
\hHorizontal whitespace
\HNon-horizontal whitespace
\vVertical whitespace
\VNon-vertical whitespace

Quantifiers

*0 or more (greedy)
+1 or more (greedy)
?0 or 1 (greedy)
{n}Exactly n times
{n,}n or more times
{n,m}Between n and m times
*?0 or more (lazy)
+?1 or more (lazy)
??0 or 1 (lazy)
*+0 or more (possessive)
++1 or more (possessive)
?+0 or 1 (possessive)

Groups and Capturing

(pattern)Capturing group
(?:pattern)Non-capturing group
(?<name>pattern)Named capturing group
(?'name'pattern)Named capturing group (alternative)
(?P<name>pattern)Python-style named group
\1Backreference to group 1
\g{1}Backreference to group 1 (alternative)
\k<name>Named backreference
\k'name'Named backreference (alternative)
\g{name}Named backreference (alternative)
(?>pattern)Atomic group

Lookarounds

(?=pattern)Positive lookahead
(?!pattern)Negative lookahead
(?<=pattern)Positive lookbehind
(?<!pattern)Negative lookbehind
(*positive_lookahead:pattern)Alternative positive lookahead syntax
(*negative_lookahead:pattern)Alternative negative lookahead syntax

Modifiers

(?i)Case insensitive
(?m)Multiline mode
(?s)Dot matches newline
(?x)Extended syntax (ignore whitespace)
(?A)ASCII-only matching
(?J)Allow duplicate names
(?U)Ungreedy (swap meaning of quantifiers)
(?-i)Turn off case insensitive
(?i:pattern)Local case insensitive

Recursion and Subroutines

(?R)Recurse entire pattern
(?0)Recurse entire pattern (alternative)
(?1)Recurse group 1
(?&name)Call named subroutine
(?P>name)Call named subroutine (Python style)
(?(DEFINE)(?<name>pattern))Define subroutine

Conditional Patterns

(?(condition)yes|no)Conditional pattern
(?(1)yes|no)If group 1 matched
(?(<name>)yes|no)If named group matched
(?(R)yes|no)If in recursion
(?(R1)yes|no)If in recursion of group 1
(?(DEFINE)pattern)Define pattern without matching

Backtracking Control

(*PRUNE)Prune backtracking
(*SKIP)Skip to next starting position
(*THEN)Force failure of enclosing group
(*COMMIT)Commit to current match
(*FAIL)Force failure
(*F)Force failure (short form)
(*ACCEPT)Force successful match

Unicode Properties

\p{L}Any letter
\p{N}Any number
\p{P}Any punctuation
\p{S}Any symbol
\p{Ll}Lowercase letter
\p{Lu}Uppercase letter
\p{Script=Latin}Latin script characters
\p{Block=BasicLatin}Basic Latin Unicode block
\P{L}Not a letter