Regular expressions are a compact language for describing text patterns. Metacharacters, quantifiers, groups, and lookaround are easy to forget, even for experienced developers. This cheat sheet collects all the main constructs with brief examples. You can conveniently test patterns in the Regex Tester on reChecker. For in-depth theory, see the complete regex guide, and for practical examples, see the article with 20 useful patterns.
Metacharacters
Main table
| Symbol | Meaning | Example |
|---|---|---|
. | Any character (except \n) | a.c → abc, a1c |
^ | Start of string | ^Hello → Hello world |
$ | End of string | end$ → the end |
* | 0 or more repetitions | go*gle → ggle, google |
+ | 1 or more repetitions | go+gle → gogle, google |
? | 0 or 1 repetition | colou?r → color, colour |
| | Alternation (OR) | cat|dog → cat or dog |
\ | Escaping | \. → a literal dot |
() | Grouping and capturing | (ab)+ → ababab |
[] | Character class | [aeiou] → vowel |
{} | Quantifier | \d{3} → exactly 3 digits |
Escaped characters
To use a metacharacter as a regular character, put \ before it:
\. \* \+ \? \\ \( \) \[ \] \{ \} \| \^ \$Examples:
\d+\.\d+ — десятичное число: 3.14
\*\*\* — три звёздочки
\[word\] — [word] как текстCharacter classes
Custom classes
| Construct | Description | Example |
|---|---|---|
[abc] | One of the characters | [aeiou] — vowel |
[a-z] | Range (lowercase) | [a-z]+ — word |
[A-Z] | Range (uppercase) | [A-Z][a-z]* — name |
[0-9] | Digits | [0-9]{4} — year |
[^abc] | Negation | [^0-9] — non-digit |
[a-zA-Z0-9] | Union | letters and digits |
Special characters inside []
^at the beginning — negation:[^0-9]-between characters — range:[a-z]-at the beginning or end — literal:[-0-9]or[0-9-]]— escape it:[\]\[]
Predefined classes
| Class | Equivalent | Description |
|---|---|---|
\d | [0-9] | Digit |
\D | [^0-9] | Non-digit |
\w | [a-zA-Z0-9_] | Word character |
\W | [^a-zA-Z0-9_] | Non-word character |
\s | [\t\n\r\f\v ] | Whitespace character |
\S | [^\t\n\r\f\v ] | Non-whitespace character |
Note: in JavaScript, \w includes Unicode letters when the u flag is set. In other languages, it includes ASCII characters only.
Special sequences
| Sequence | Description |
|---|---|
\n | Line feed |
\r | Carriage return |
\t | Tab |
\0 | Null byte |
\xHH | Character by hex value (for example, \x41 = A) |
\uHHHH | Unicode (for example, \u0410 = А) |
Quantifiers
Basic quantifiers
| Quantifier | Meaning | Example |
|---|---|---|
* | 0 or more | \d* — digits or empty |
+ | 1 or more | \d+ — one or more digits |
? | 0 or 1 | -?\d+ — number with an optional minus sign |
{n} | Exactly n | \d{4} — exactly 4 digits |
{n,} | n or more | [a-z]{3,} — 3+ letters |
{n,m} | From n to m | \d{2,4} — from 2 to 4 digits |
Greediness
| Type | Syntax | Behavior |
|---|---|---|
| Greedy | *, +, ?, {n,m} | Matches as much as possible |
| Lazy | *?, +?, ??, {n,m}? | Matches as little as possible |
| Possessive (PCRE) | *+, ++, ?+ | Greedy, without backtracking |
Example:
Текст: <b>жирный</b> и <b>ещё</b>
<b>.*</b> → одно совпадение: <b>жирный</b> и <b>ещё</b>
<b>.*?</b> → два совпадения: <b>жирный</b>, <b>ещё</b>Anchors and boundaries
| Construct | Description |
|---|---|
^ | Start of string (or line with the m flag) |
$ | End of string (or line with the m flag) |
\A | Start of the entire text (independent of m) |
\Z | End of the entire text |
\b | Word boundary (between \w and \W) |
\B | Non-word boundary |
Examples:
^\d+$ — строка целиком из цифр
\bword\b — слово «word» целиком
\Bcat\B — «cat» внутри слова (concatenate)Groups
Capturing groups
| Syntax | Description |
|---|---|
(...) | Capturing group |
(?:...) | Non-capturing group |
(?<name>...) | Named group (JS, PCRE) |
(?P<name>...) | Named group (Python) |
Examples:
(\d{2})\.(\d{2})\.(\d{4}) — дата, группы 1, 2, 3
(?:https?):// — протокол без захвата
(?<year>\d{4})-(?<month>\d{2}) — именованные группыBackreferences
| Syntax | Description |
|---|---|
\1, \2, ... | Reference to a group by number |
\k<name> | Reference to a named group (JS, PCRE) |
(?P=name) | Reference to a named group (Python) |
Examples:
(\w+)\s+\1 — повторяющееся слово
(['"]).*?\1 — строка в кавычках
<(\w+)>.*?</\1> — парный HTML-тегLookahead and lookbehind
Lookahead
| Syntax | Name | Description |
|---|---|---|
(?=...) | Positive lookahead | Must be followed by ... |
(?!...) | Negative lookahead | Must not be followed by ... |
Examples:
\d+(?=\s*руб) — число перед «руб»
\w+(?=\.) — слово перед точкой
^(?!.*admin) — строка без «admin»Lookbehind
| Syntax | Name | Description |
|---|---|---|
(?<=...) | Positive lookbehind | Must be preceded by ... |
(?<!...) | Negative lookbehind | Must not be preceded by ... |
Examples:
(?<=\$)\d+ — число после $
(?<=class=")[^"]+ — значение атрибута class
(?<!\d)\d{3} — 3 цифры не после цифрыCombining lookarounds
(?<=<b>).*?(?=</b>) — содержимое между <b> и </b>
(?<!un)happy — happy, но не unhappyFlags (modifiers)
| Flag | JavaScript | Python | PHP | Description |
|---|---|---|---|---|
i | i | re.I | i | Ignore case |
g | g | — | g | Global search (all matches) |
m | m | re.M | m | Multiline (^ and $ apply to each line) |
s | s | re.S | s | Dot matches \n |
u | u | re.U | u | Unicode (important for \p{}) |
x | — | re.X | x | Ignore whitespace and comments |
Usage
// JavaScript
'Hello'.match(/hello/i); // ['Hello']
'1 2 3'.match(/\d/g); // ['1', '2', '3']# Python
re.search(r'hello', 'Hello', re.I)
re.findall(r'\d', '1 2 3')// PHP
preg_match('/hello/i', 'Hello');
preg_match_all('/\d/', '1 2 3', $m);Unicode character classes (extended)
In Unicode mode (u in JS, re.UNICODE in Python), these are available:
| Class | Description |
|---|---|
\p{L} | Letter |
\p{N} | Number |
\p{P} | Punctuation |
\p{S} | Symbol |
\p{Z} | Whitespace |
\p{Script=Cyrillic} | Cyrillic |
\p{Script=Latin} | Latin |
Negation: \P{L} — not a letter.
Examples:
\p{L}+ — последовательность букв (в т.ч. кириллица)
[\p{L}\p{N}\s]+ — слова с цифрами и пробелами
\p{Script=Cyrillic}+ — только кириллицаSpecial constructs
Conditional expressions (PCRE)
(?(condition)yes-pattern|no-pattern)Example: match text in quotes or without quotes:
(?(?=['"])(['"]).*?\1|[\w\s]+)Atomic groups (PCRE)
(?>pattern)A group without backtracking — like a possessive quantifier applied to the whole pattern.
Comments (x flag)
\d{2} # день
\. # разделитель
\d{2} # месяцOperator precedence
From highest to lowest:
- Quantifiers
*,+,?,{} - Concatenation (sequence)
- Alternation
|
Example: a|bc is interpreted as a or bc, not ab or c.
Escaping in different languages
JavaScript
const re = /\d+/; // Литерал
const re2 = new RegExp('\\d+'); // Строка — двойное экранированиеPython
re.compile(r'\d+') # raw string — один \
re.compile('\\d+') # обычная строка — двойное \\PHP
preg_match('/\d+/', $str); # В строках PHP \d → d, нужен \\
preg_match('/\\d+/', $str); # или один \ в паттернеPerformance
Recommendations for avoiding catastrophic backtracking:
- Avoid nested quantifiers:
(a+)+,(.*)* - Use atomic groups or possessive quantifiers
- Narrow patterns:
[^>]+instead of.*inside tags - Specify boundaries explicitly:
\d{4}instead of\d+for a year
Quick reference: feature support
| Construct | JS | Python | PHP | Java |
|---|---|---|---|---|
| Named groups | ES2018 | Yes | Yes | Yes |
| Lookbehind | ES2018 | Yes | Yes | Yes |
| Unicode \p | With the u flag | Yes | Yes | Yes |
| Atomic groups | No | No | Yes | Yes |
| Recursion | No | No | Yes | No |
Modes in .NET
| Construct | Description |
|---|---|
(?i) | Enable ignore-case mode |
(?-i) | Disable ignore-case mode |
(?m) | Multiline mode |
(?s) | Singleline (dot = any character) |
(?x) | Ignore whitespace |
JavaScript has no built-in inline modifiers. In Python, use (?i) and equivalents.
Boundaries in different contexts
Word boundary \b
\b depends on the definition of “word.” In ASCII, this is [a-zA-Z0-9_]. In Unicode mode, it is an extended set. Be careful with Cyrillic: in older engines, \b may not work for non-ASCII characters.
Start/end boundaries
^and$— start and end of the entire string by default- With the
mflag — start and end of each line in multiline text \Aand\Z— always the start and end of the text (independent ofm)
Replacing with groups
Numbered groups
'2026-03-07'.replace(/(\d{4})-(\d{2})-(\d{2})/, '$3.$2.$1');
// '07.03.2026'Named groups (ES2018)
'John Doe'.replace(/(?<first>\w+)\s+(?<last>\w+)/, '$<last>, $<first>');
// 'Doe, John'Transforming during replacement
'hello world'.replace(/\b\w/g, m => m.toUpperCase());
// 'Hello World'Common mistakes
| Mistake | Incorrect | Correct |
|---|---|---|
| Dot as a literal | file.txt | file\.txt |
| Square brackets | [0-9] for one digit | [0-9] or \d |
| Greediness | .* for “up to the first” | .*? or [^X]* |
| Boundaries | \d+ for an integer | \b\d+\b or ^\d+$ |
| Escaping in a string | "\d" in JS | "\\d" or /\d/ |
Related materials
For an in-depth guide with theory and examples, see the complete regex guide. Ready-made patterns for common tasks are in 20 useful regular expressions. You can test a pattern in the Regex Tester.