Regular Expressions Cheat Sheet
1. Basic Patterns
. Any character except newline
^ Start of line
$ End of line
* Zero or more repetitions
+ One or more repetitions
? Zero or one repetition
{n} Exactly n repetitions
{n,} n or more repetitions
{n,m} Between n and m repetitions
2. Character Classes
[abc] One of a, b, or c
[^abc] Not a, b, or c
[a-z] Lowercase a to z
[A-Z] Uppercase A to Z
[0-9] Digit 0 to 9
3. Special Sequences
\d Any digit
Regular Expressions Cheat Sheet
\D Non-digit
\w Word character (letter, digit, underscore)
\W Non-word character
\s Whitespace (space, tab, newline)
\S Non-whitespace
4. Other Important Patterns
| OR
(pattern) Grouping
(?P<name>pattern) Named Group
5. Key Differences with Examples
* vs +: * allows 0 or more, + requires at least 1
\d vs [0-9]: Same effect
\w vs [a-zA-Z0-9_]: Equivalent
\s vs [ \t\n\r\f\v]: Equivalent
^ vs \A: ^ start of line, \A start of entire text
Example Codes:
import re
text = "ab abb abbb a"
Regular Expressions Cheat Sheet
re.findall(r'ab*', text) # ['ab', 'abb', 'abbb', 'a']
re.findall(r'ab+', text) # ['ab', 'abb', 'abbb']
re.findall(r'cat|dog', 'I have a cat and a dog') # ['cat', 'dog']
text = """hello world
goodbye world"""
re.findall(r'^goodbye', text, re.M) # ['goodbye']
re.findall(r'\Agoodbye', text) # []
Useful Sites:
- https://regex101.com
- https://regexr.com