Scope. Regex syntax depends on the engine and flags. In Python string patterns, \d and \w include Unicode characters unless ASCII mode is selected. Named groups and lookbehind differ between Python, JavaScript, Java and PCRE.
Matching Characters
| Pattern | Meaning |
|---|---|
[abc] |
Matches any single character: a, b, or c |
[^abc] |
Matches any single character except: a, b, or c. "^" is only valid as the first character |
[a-g] |
Matches any single character in the range a-g |
[^a-g] |
Matches any single character NOT in the range a-g |
[H-N] |
Matches any single character in the range H-N |
[0-9] |
Matches any single digit in the range 0-9 |
[a-gH-N] |
Matches any single character in the range a-g or H-N |
| Wildcards: | |
. |
[^\n\r], matches any character except newline |
\s |
whitespace character, i.e., newline, tab, space, etc. |
\S |
[^\s], any non-whitespace character |
\d |
Digit character; Unicode or ASCII depends on the engine and flags |
\D |
[^\d], any non-digit character |
\w |
Word character; its definition depends on the engine and flags |
\W |
[^\w], any non-word character |
Matching Groups
| Pattern | Meaning |
|---|---|
(a|b) |
Matches a or b and captures |
(...) |
Capturing group |
(?:...) |
Non-capturing group |
(?P<name>...) / (?<name>...) |
Named capture: Python / modern JavaScript and Java |
(?(condition)true_regex|false_regex) |
Conditional matching (Python/PCRE; not JavaScript) |
group(0) is used to get the entire match result. group(n) can get sub-capturing groups from the entire match result.
Python uses (?P<name>...); modern JavaScript and Java use (?<name>...). Conditional groups are engine-specific and are not supported by JavaScript.
Frequency Range
| Pattern | Meaning |
|---|---|
{3} |
Preceding item appears exactly 3 times, equivalent to {3,3} |
{3,6} |
Preceding item appears between 3 and 6 times |
{3,} |
Preceding item appears at least 3 times |
{0,6} |
Preceding item appears at most 6 times |
| Wildcards: | |
* |
{0,} Zero or more |
+ |
{1,} One or more |
? |
{0,1} Zero or one |
\w* |
Greedy mode |
\w*? |
Non-greedy (lazy) mode |
Anchors
| Pattern | Meaning |
|---|---|
^ |
Start of string |
$ |
End of string |
\b |
Boundary, word boundary |
\B |
Non-word boundary |
| Lookaround Assertions: | |
(?=exp) |
Positive lookahead (suffix is exp) |
(?<=exp) |
Positive lookbehind (prefix is exp) |
(?!exp) |
Negative lookahead (suffix is NOT exp) |
(?<!exp) |
Negative lookbehind (prefix is NOT exp) |
Official reference
Named capture example in Python
import re
match = re.fullmatch(r"(?P<word>\w+)", "café")
print(match.group("word")) # café
print(re.fullmatch(r"\w+", "café", flags=re.ASCII)) # None