N regex cheat sheet: character classes, quantifiers, anchors, groups and greedy vs lazy, in python - Netscape _ □ ×
Back Forward Home Reload Guides Sign
URL: http://www.nicnonac.com/guides/regex-cheat-sheet/
☷ regex cheat sheet: character classes, quantifiers, anchors, groups and greedy vs lazy, in python - nicnonac guides _□×

← back to guides

regex cheat sheet: character classes, quantifiers, anchors, groups and greedy vs lazy, in python

Stacks · 11 min read · posted Nov 30, 2026, 4:07 pm

Most of the regex you'll run into is built from the same five things: character classes, quantifiers, anchors, groups, and greedy vs lazy. Once you can read those, a pattern stops looking like line noise and starts reading left to right like a sentence.

This is the cheat sheet from the reel. There's a symbol lookup table first, then a section for each of the five: when you reach for it, the syntax with a small example and what it printed, the mistake that usually bites, and a few patterns to practise on. Answers are in brackets, and they're all run together at the end.

Every example here was run on Python 3.14.6 with the built-in re module, and the output under each block is what it printed. Near the end there's a short section on what changes in JavaScript and in grep, and only differences that were actually run are in it.

the symbol lookup

symbol means example matches
. any character except a newline c.t cat, cot, c9t
\d a digit \d\d 42
\w a letter, digit or underscore \w+ user_7
\s whitespace: space, tab, newline a\sb a b
\D \W \S the opposite of \d \w \s \D+ abc
[abc] one of a, b or c gr[ae]y grey, gray
[a-z] one character in a range [A-Z] Q
[^abc] one character that is not a, b or c [^0-9] x
* zero or more of the thing before bo* b, bo, booo
+ one or more bo+ bo, booo
? zero or one colou?r color, colour
{3} exactly three \d{3} 123
{2,4} two to four \d{2,4} 12, 1234
{2,} two or more \d{2,} 12, 12345
^ start of the string ^Hi Hi there
$ end of the string end$ the end
\b the edge of a word \bcat\b cat, not cats
( ) a group that captures (\d+)-(\d+) 10-20, gives 10 and 20
(?: ) a group that doesn't capture (?:ha)+ haha
(?P<name> ) a named group (?P<year>\d{4}) 2026
| or cat|dog cat, dog
*? +? ?? lazy: as few as possible <.*?> <b>
\. \* \( the character itself, not its meaning 3\.14 3.14

the quick lookup

i need to write
does it appear anywhere re.search(p, s)
does the whole string match re.fullmatch(p, s)
every match, as a list re.findall(p, s)
every match, with its position re.finditer(p, s)
replace every match re.sub(p, new, s)
split on a pattern re.split(p, s)
pull parts out of a match m.group(1), m.groups()
match across lines re.MULTILINE for ^ $, re.DOTALL for .

before you start: raw strings and the re functions

Always write patterns as raw strings, r"...". In a normal string Python reads the backslashes first, and "\b" turns into a single backspace character before re ever sees it:

import re

print(len("\b"), len(r"\b"))
print(re.findall("\bcat\b", "a cat"))
print(re.findall(r"\bcat\b", "a cat"))
1 2
[]
['cat']

No error, just no matches, which is why it's so easy to miss.

These are the functions you'll use. search looks anywhere in the string, match only at the start, and fullmatch wants the whole string. Each returns a match object or None.

import re

s = "order 66 shipped, order 7 late"
print(re.search(r"\d+", s))
print(re.search(r"\d+", s).group())
print(re.match(r"\d+", s))
print(re.fullmatch(r"\d+", "66"))
print(re.findall(r"\d+", s))
print([m.span() for m in re.finditer(r"\d+", s)])
print(re.sub(r"\d+", "#", s))
print(re.split(r",\s*", s))
<re.Match object; span=(6, 8), match='66'>
66
None
<re.Match object; span=(0, 2), match='66'>
['66', '7']
[(6, 8), (24, 25)]
order # shipped, order # late
['order 66 shipped', 'order 7 late']

span=(6, 8) means the match starts at index 6 and stops before index 8, the same way slicing works.

1. character classes

When you reach for it. You care what kind of character goes in a spot, not which exact one: any digit, any letter, anything that isn't a space.

The syntax. \d, \w and \s are shorthands for digits, word characters and whitespace. Square brackets make your own set: [aeiou] is one vowel, [a-z] is one lowercase letter. A ^ straight after the opening bracket flips it, so [^0-9] is one character that isn't a digit. Either way, a class matches exactly one character.

import re

s = "Jo_7 got #25!"

print(re.findall(r"\d", s))
print(re.findall(r"\w", s))
print(re.findall(r"[a-z]", s))
print(re.findall(r"[^\w\s]", s))
['7', '2', '5']
['J', 'o', '_', '7', 'g', 'o', 't', '2', '5']
['o', 'g', 'o', 't']
['#', '!']

This is the one in the reel. \w takes the underscore and the digits as well as the letters. [a-z] skips the capital J. [^\w\s] is "not a word character and not a space", which leaves the symbols.

More shapes. Inside square brackets most symbols lose their meaning, so [.] is a plain dot. A - at the end of the set is a plain hyphen. Capital \D \W \S are the opposites.

import re

s = "Hi Jo! Call 021-555 at 9.30"
print(re.findall(r"\s", s))
print(re.findall(r"[aeiou]", s))
print(re.findall(r"[A-Z]", s))
print(re.findall(r"[0-9-]", s))
print(re.findall(r"\D", "a1-b2"))
print(re.findall(r"[.]", s))
[' ', ' ', ' ', ' ', ' ']
['i', 'o', 'a', 'a']
['H', 'J', 'C']
['0', '2', '1', '-', '5', '5', '5', '9', '3', '0']
['a', '-', 'b']
['.']

What bites. The unescaped dot. Outside square brackets . means any character, so a pattern meant for 3.14 also matches 3x14. Write \. when you mean a dot. The other one is \w in Python 3: it matches letters from any language, so é counts. Add re.ASCII if you only want a to z.

import re

print(re.findall(r"3.14", "pi is 3.14, not 3x14"))
print(re.findall(r"3\.14", "pi is 3.14, not 3x14"))
print(re.findall(r"\w", "café_9"))
print(re.findall(r"\w", "café_9", re.ASCII))
['3.14', '3x14']
['3.14']
['c', 'a', 'f', 'é', '_', '9']
['c', 'a', 'f', '_', '9']

Practise.

  • Every hashtag in "loving #python and #regex_101 today". (#\w+)
  • Every character in "a1-b2" that isn't a letter. ([^a-zA-Z])
  • Every vowel, upper or lower case. ([aeiouAEIOU])

2. quantifiers

When you reach for it. You know what kind of character comes next but not how many: a number of any length, an optional letter, exactly four digits.

The syntax. A quantifier goes straight after the thing it repeats. * is zero or more, + is one or more, ? is zero or one, and {m,n} is between m and n.

import re

s = "b bo booooo"

print(re.findall(r"bo*", s))
print(re.findall(r"bo+", s))
print(re.findall(r"bo?", s))
print(re.findall(r"bo{2,4}", s))
['b', 'bo', 'booooo']
['bo', 'booooo']
['b', 'bo', 'bo']
['boooo']

This is the one in the reel. Same text, four counts of o. + drops the lone b because it needs at least one o. ? takes one o at most. {2,4} skips b and bo, then stops at four o's and leaves the fifth behind.

More shapes.

import re

print(re.findall(r"\d+", "7 cats, 42 dogs, 1000 fish"))
print(re.findall(r"\d{3}", "1234567"))
print(re.findall(r"\d{2,}", "1 22 333"))
print(re.findall(r"colou?r", "color colour colouur"))
['7', '42', '1000']
['123', '456']
['22', '333']
['color', 'colour']

\d+ is the one you'll write most: a whole number, however long. \d{3} on seven digits finds two matches and leaves the 7, because matches don't overlap.

What bites. A quantifier only repeats the one thing right before it. ab+ is an a and then one or more b's, not "ab" repeated. Put it in a group, (ab)+, to repeat the pair. The other one is * matching nothing. Zero is a valid count, so \d* finds an empty match at every spot without a digit. Use + when you need at least one.

import re

print(re.findall(r"ab+", "abab abbb"))
print(re.fullmatch(r"(ab)+", "abab"))
print(re.findall(r"\d*", "a1b"))
print(re.findall(r"\d+", "a1b"))
['ab', 'ab', 'abbb']
<re.Match object; span=(0, 4), match='abab'>
['', '1', '', '']
['1']

Practise.

  • Squash every run of spaces in "too many spaces" down to one space. (re.sub(r"\s+", " ", s))
  • Both spellings of grey and gray. (gr[ae]y, a class, not a quantifier, which is the point)
  • Numbers with at least two digits in "1 22 333". (\d{2,})

3. anchors

When you reach for it. The match has to sit in a particular place: at the start, at the end, or as a whole word rather than inside a longer one. Validating input is mostly anchors.

The syntax. ^ is the start of the string, $ is the end, and \b is the edge of a word, the gap between a word character and anything else. None of them use up a character. They match a position.

import re

s = "cats a cat scat"

print(re.sub(r"cat", "dog", s))
print(re.sub(r"^cat", "dog", s))
print(re.sub(r"cat$", "dog", s))
print(re.sub(r"\bcat\b", "dog", s))
dogs a dog sdog
dogs a cat scat
cats a cat sdog
cats a dog scat

This is the one in the reel. With no anchor every "cat" gets replaced, even inside other words. ^ keeps only the one at the start, $ only the one at the end, and \b on both sides keeps only the standalone word.

More shapes. To check that a whole string is a four digit PIN, anchor both ends, or use fullmatch, which does the same thing. With re.MULTILINE, ^ and $ work per line instead of per string.

import re

pin = r"\d{4}"
for s in ["1234", "12345", "pin 1234"]:
    print(s, bool(re.search(pin, s)), bool(re.search(r"^\d{4}$", s)), bool(re.fullmatch(pin, s)))

log = "ok: start\nerror: disk\nok: done"
print(re.findall(r"^\w+", log))
print(re.findall(r"^\w+", log, re.MULTILINE))
1234 True True True
12345 True False False
pin 1234 True False False
['ok']
['ok', 'error', 'ok']

Without the anchors, "12345" passes as a PIN, because four of its digits are a match.

What bites. Mixing up match and search. re.match is anchored to the start without you writing ^, so it misses a number in the middle. The other one is $ letting a trailing newline through: it matches just before a final \n, so ^\d{4}$ accepts "1234\n". fullmatch doesn't.

import re

print(re.match(r"\d+", "id 42"))
print(re.search(r"\d+", "id 42"))
print(re.search(r"^\d{4}$", "1234\n"))
print(re.fullmatch(r"\d{4}", "1234\n"))
None
<re.Match object; span=(3, 5), match='42'>
<re.Match object; span=(0, 4), match='1234'>
None

Practise.

  • Is "555-1234" exactly three digits, a hyphen and four digits? Is "555-12345"? (re.fullmatch(r"\d{3}-\d{4}", s): True, then False)
  • Every word in "Ana met Ben in Oslo" that starts with a capital. (\b[A-Z]\w*)
  • The first word of every line in a log. (^\w+ with re.MULTILINE)

4. groups

When you reach for it. You want parts of the match, not just the whole thing: the year, month and day out of a date, the user and domain out of an email. Or you want "this or that" with |.

The syntax. Brackets make a group, and each group captures what it matched. Groups are numbered by their opening bracket, left to right, from 1. m.group(0) is the whole match. | means or, and inside a group it only covers that group.

import re

s = "to: ana@site.org"
p = r"(\w+)@(\w+)\.(com|org)"

m = re.search(p, s)
print(m.group(0))
print(m.group(1))
print(m.groups())
print(m.span(2))
ana@site.org
ana
('ana', 'site', 'org')
(8, 12)

This is the one in the reel. Group 3 is (com|org): it tries com first, that fails, then org matches.

More shapes. (?P<name>...) gives a group a name. In re.sub the replacement can use \1, \2 to put groups back in a new order. findall with groups returns the groups, as tuples when there's more than one. (?:...) groups without capturing, for when you only need the brackets to repeat something.

import re

m = re.search(r"(?P<y>\d{4})-(?P<m>\d\d)-(?P<d>\d\d)", "due 2026-11-30")
print(m.group("y"))
print(m.groupdict())

print(re.sub(r"(\d{4})-(\d\d)-(\d\d)", r"\3/\2/\1", "due 2026-11-30"))
print(re.findall(r"(\w+)=(\d+)", "a=1, b=22"))
print(re.findall(r"(?:ha)+", "haha hahaha"))
print(re.findall(r"cat|dog", "a dog, a cat"))
2026
{'y': '2026', 'm': '11', 'd': '30'}
due 30/11/2026
[('a', '1'), ('b', '22')]
['haha', 'hahaha']
['dog', 'cat']

What bites. findall with a capturing group gives you the group, not the match. (ha)+ matches "haha" and "hahaha", but a repeated group only keeps its last round, so you get 'ha' twice. Use (?:...) when you want the whole match back. The other one is how far | reaches. It splits the whole pattern unless a group stops it, so ^cat|dog$ means "cat at the start, or dog at the end", not "the whole string is cat or dog".

import re

print(re.findall(r"(ha)+", "haha hahaha"))
print(re.findall(r"^cat|dog$", "catdog"))
print(re.findall(r"^cat|dog$", "hotdog"))
print(re.fullmatch(r"cat|dog", "catdog"))
print(re.fullmatch(r"(cat|dog)+", "catdog"))
['ha', 'ha']
['cat', 'dog']
['dog']
None
<re.Match object; span=(0, 6), match='catdog'>

Practise.

  • Swap the two words in "hello world". (re.sub(r"(\w+) (\w+)", r"\2 \1", s))
  • Every key and value in "a=1, b=22" as pairs. ((\w+)=(\d+) with findall)
  • The year, month and day of a date by name. ((?P<y>\d{4})-(?P<m>\d\d)-(?P<d>\d\d) and groupdict())

5. greedy vs lazy

When you reach for it. Your pattern has .* or .+ between two markers, like quotes or tags, and the match runs much further than you meant.

The idea. Quantifiers are greedy by default: they take as much as they can and only give back what the rest of the pattern needs. Put a ? after one, *? or +?, and it turns lazy: it takes as little as it can and stops at the first place the rest of the pattern fits.

import re

s = "<b>hi</b>"

print(re.findall(r"<.*>", s))
print(re.findall(r"<.*?>", s))
['<b>hi</b>']
['<b>', '</b>']

This is the one in the reel. Greedy .* runs to the end of the string and backs off to the last >, so the whole thing is one match. Lazy .*? stops at the first >, so you get each tag.

More shapes. Pulling quoted text out of a string is the everyday version. A negated class, [^"]* ("anything but a quote"), gets the same result as the lazy version, and it can't run past the closing quote at all. Add a group to get the text without its quotes.

import re

s = 'say "hi" and "bye"'
print(re.findall(r'".*"', s))
print(re.findall(r'".*?"', s))
print(re.findall(r'"[^"]*"', s))
print(re.findall(r'"(.*?)"', s))
['"hi" and "bye"']
['"hi"', '"bye"']
['"hi"', '"bye"']
['hi', 'bye']

What bites. . doesn't match a newline, so a pattern that should span two lines finds nothing. re.DOTALL changes that. The other one is a lazy quantifier at the very end of a pattern. With nothing after it to stop at, it takes as little as possible, which is nothing for *? and one character for +?.

import re

html = "<p>one\ntwo</p>"
print(re.findall(r"<p>(.*)</p>", html))
print(re.findall(r"<p>(.*)</p>", html, re.DOTALL))
print(re.findall(r"a.*?", "abc"))
print(re.findall(r"\d+?", "123"))
[]
['one\ntwo']
['a']
['1', '2', '3']

Regex is fine for small, predictable bits of HTML like these. For real pages, use an HTML parser.

Practise.

  • The text inside each pair of square brackets in "[info] ok [warn] low disk". (\[(.*?)\])
  • The same, without a lazy quantifier. (\[([^\]]*)\])
  • Every quoted word in 'say "hi" and "bye"', quotes removed. ("(.*?)")

the answers, run

import re

print(re.findall(r"#\w+", "loving #python and #regex_101 today"))
print(bool(re.fullmatch(r"\d{3}-\d{4}", "555-1234")), bool(re.fullmatch(r"\d{3}-\d{4}", "555-12345")))
print(re.sub(r"\s+", " ", "too    many   spaces"))
print(re.findall(r"\b[A-Z]\w*", "Ana met Ben in Oslo"))
print(re.sub(r"(\w+) (\w+)", r"\2 \1", "hello world"))
print(re.findall(r"\[(.*?)\]", "[info] ok [warn] low disk"))
['#python', '#regex_101']
True False
too many spaces
['Ana', 'Ben', 'Oslo']
world hello
['info', 'warn']
import re

print(re.findall(r"[^a-zA-Z]", "a1-b2"))
print(re.findall(r"[aeiouAEIOU]", "An Owl ate"))
print(re.findall(r"gr[ae]y", "grey gray groy"))
print(re.findall(r"\d{2,}", "1 22 333"))
print(re.findall(r"^\w+", "ok: start\nerror: disk", re.MULTILINE))
print(re.findall(r"(\w+)=(\d+)", "a=1, b=22"))
print(re.search(r"(?P<y>\d{4})-(?P<m>\d\d)-(?P<d>\d\d)", "2026-11-30").groupdict())
print(re.findall(r"\[([^\]]*)\]", "[info] ok [warn] low disk"))
print(re.findall(r'"(.*?)"', 'say "hi" and "bye"'))
['1', '-', '2']
['A', 'O', 'a', 'e']
['grey', 'gray']
['22', '333']
['ok', 'error']
[('a', '1'), ('b', '22')]
{'y': '2026', 'm': '11', 'd': '30'}
['info', 'warn']
['hi', 'bye']

the same pattern elsewhere

Most of this carries over to other languages, but a few things don't. These are the differences that came up when the same patterns were run in JavaScript (Node 26.8.1) and in the grep that ships with macOS (grep -E, BSD grep 2.6.0). Nothing else was tested, so other tools and versions may differ.

JavaScript.

const s = "cats a cat scat";
console.log(s.replace(/cat/, "dog"));
console.log(s.replace(/cat/g, "dog"));
console.log(s.replace(/\bcat\b/g, "dog"));

const date = "due 2026-11-30";
console.log(date.match(/(?<y>\d{4})-(?<m>\d\d)-(?<d>\d\d)/).groups.y);
console.log(date.replace(/(\d{4})-(\d\d)-(\d\d)/, "$3/$2/$1"));
console.log("a=1, b=22".match(/(\w+)=(\d+)/g));
console.log([..."a=1, b=22".matchAll(/(\w+)=(\d+)/g)].map(m => [m[1], m[2]]));
console.log("<b>hi</b>".match(/<.*?>/g));
dogs a cat scat
dogs a dog sdog
cats a dog scat
2026
due 30/11/2026
[ 'a=1', 'b=22' ]
[ [ 'a', '1' ], [ 'b', '22' ] ]
[ '<b>', '</b>' ]
  • replace without the g flag only replaces the first match. Python's re.sub replaces all of them unless you pass count.
  • Named groups are (?<y>...) in JavaScript and (?P<y>...) in Python. Python 3.14.6 rejects the JavaScript form (below).
  • A replacement refers to groups as $1 in JavaScript and \1 in Python.
  • match with the g flag returns whole matches and drops the groups. Python's findall returns the groups. matchAll is the JavaScript way to get them.
  • \b and lazy .*? gave the same results as Python here.
import re

try:
    re.compile(r"(?<y>\d{4})")
except re.error as e:
    print("re.error:", e)
print(re.search(r"(?P<y>\d{4})", "in 2026").group("y"))
re.error: unknown extension ?<y at position 1
2026

grep -E on macOS. -o prints each match on its own line.

$ printf 'cats a cat scat\n' | grep -oE '\bcat\b'
cat
$ printf '<b>hi</b>\n' | grep -oE '<.*?>'
<b>
</b>
$ printf 'a1 b22\n' | grep -oE '[[:digit:]]+'
1
22
$ printf 'a1 b22\n' | grep -oE '\d+'
1
22
$ printf 'due 2026-11-30\n' | grep -oE '(?P<y>[0-9]{4})'
grep: repetition-operator operand invalid
  • \b, \d and .*? worked the same as in Python on these inputs.
  • grep understands POSIX classes like [[:digit:]]. Python doesn't: it reads them as an ordinary set, finds nothing here, and prints a FutureWarning: Possible nested set to stderr.
  • grep has no named groups. (?P<y>...) is an error.
import re

print(re.findall(r"[[:digit:]]+", "a1 b22"))
print(re.findall(r"\d+", "a1 b22"))
[]
['1', '22']

how to practise with this

One section at a time. Write the pattern before you run it, then run it on a string that should match and one that shouldn't. The one that shouldn't is where most bugs show up.

When a pattern gets long, read it out left to right: "a word, an at sign, a word, a dot, then com or org". If you can't say it in one sentence, split it into two smaller patterns.

honest limitations

Five things isn't all of regex. Lookaheads and lookbehinds ((?=...), (?<=...)), backreferences inside the pattern ((\w)\1 for a doubled letter) and flags like re.IGNORECASE and re.VERBOSE all come up, and they build on these five.

Regex is the wrong tool for some jobs. Real email validation, HTML and anything nested (like balanced brackets) need a proper parser or library. A pattern that works on the examples you tried can still accept or reject things you didn't think of.

Everything here was run on Python 3.14.6. The JavaScript and grep notes only cover what was run, on Node 26.8.1 and the grep that ships with macOS. GNU grep on Linux, PCRE and other engines each have their own details.

← all guides

Done nicnonac.com 56.6k