0% found this document useful (0 votes)
20 views7 pages

Python Regex Cheat Sheet Guide

This document is a comprehensive cheatsheet for Python regular expressions, detailing basic patterns, character classes, anchors, grouping, lookaheads, lookbehinds, quantifiers, flags, substitution, splitting, finding, and match object methods. It also includes advanced topics like backreferences, conditional matching, atomic grouping, possessive quantifiers, and common patterns for various data formats. The content is authored by Waleed Mousa and serves as a quick reference for users working with regular expressions in Python.

Uploaded by

Nimit Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views7 pages

Python Regex Cheat Sheet Guide

This document is a comprehensive cheatsheet for Python regular expressions, detailing basic patterns, character classes, anchors, grouping, lookaheads, lookbehinds, quantifiers, flags, substitution, splitting, finding, and match object methods. It also includes advanced topics like backreferences, conditional matching, atomic grouping, possessive quantifiers, and common patterns for various data formats. The content is authored by Waleed Mousa and serves as a quick reference for users working with regular expressions in Python.

Uploaded by

Nimit Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

# [ Python Regular Expression ] [ cheatsheet ]

1. Basic Patterns

● . - Matches any single character except a newline


● ^ - Matches the start of the string
● $ - Matches the end of the string
● * - Matches zero or more occurrences of the preceding character or group
● + - Matches one or more occurrences of the preceding character or group
● ? - Matches zero or one occurrence of the preceding character or group
● {n} - Matches exactly n occurrences of the preceding character or group
● {n,} - Matches n or more occurrences of the preceding character or group
● {n,m} - Matches between n and m occurrences of the preceding character
or group
● [] - Defines a character set, matches any single character within the
brackets
● [^] - Defines a negated character set, matches any single character not
within the brackets
● | - Matches either the expression before or after the pipe

1.1 Basic Matching

● Match a specific string: [Link](r'hello', string)


● Match at the start of a string: [Link](r'^hello', string)
● Match at the end of a string: [Link](r'world$', string)
● Case-insensitive matching: [Link](r'hello', string, [Link])

2. Character Classes

● \d - [Link](r'\d', string) - Matches any digit (0-9)


● \D - [Link](r'\D', string) - Matches any non-digit character
● \w - [Link](r'\w', string) - Matches any word character (alphanumeric
characters and underscore)
● \W - [Link](r'\W', string) - Matches any non-word character
● \s - [Link](r'\s', string) - Matches any whitespace character (space,
tab, newline)
● \S - [Link](r'\S', string) - Matches any non-whitespace character

By: Waleed Mousa


3. Anchors

● \b - [Link](r'\b', string) - Matches a word boundary (position


between a word character and a non-word character)
● \B - [Link](r'\B', string) - Matches a non-word boundary
● \A - [Link](r'\A', string) - Matches the start of the string (similar
to ^, but doesn't match after a newline)
● \Z - [Link](r'\Z', string) - Matches the end of the string (similar
to $, but doesn't match before a newline)

4. Grouping and Capturing

● (...) - Creates a capturing group


● (?:...) - Creates a non-capturing group
● (?P<name>...) - Creates a named capturing group
● \1, \2, etc. - Matches the text captured by the corresponding group
● (?P=name) - Matches the text captured by the named group
● Group a pattern: [Link](r'(abc)', string)
● Capture a group: [Link](r'(abc)', string).group(1)
● Match any of the specified characters: [Link](r'[aeiou]', string)
● Match any character except the specified ones: [Link](r'[^aeiou]',
string)
● Match a range of characters: [Link](r'[a-z]', string)
● Match a range of characters and digits: [Link](r'[a-zA-Z0-9]', string)

5. Lookahead and Lookbehind

● (?=...) - [Link](r'foo(?=bar)', string) - Positive lookahead, matches


if the pattern inside the lookahead matches
● (?!...) - [Link](r'foo(?!bar)', string) - Negative lookahead, matches
if the pattern inside the lookahead doesn't match
● (?<=...) - [Link](r'(?<=foo)bar', string) - Positive lookbehind,
matches if the pattern inside the lookbehind matches
● (?<!...) - [Link](r'(?<!foo)bar', string) - Negative lookbehind,
matches if the pattern inside the lookbehind doesn't match

6. Quantifiers

● *? - Non-greedy version of *, matches as few occurrences as possible

By: Waleed Mousa


● +? - Non-greedy version of +, matches as few occurrences as possible
● ?? - Non-greedy version of ?, matches zero or one occurrence
● {n,}? - Non-greedy version of {n,}, matches as few occurrences as
possible
● {n,m}? - Non-greedy version of {n,m}, matches as few occurrences as
possible
● Match zero or more occurrences: [Link](r'a*', string)
● Match one or more occurrences: [Link](r'a+', string)
● Match zero or one occurrence: [Link](r'a?', string)
● Match exactly n occurrences: [Link](r'a{3}', string)
● Match at least n occurrences: [Link](r'a{3,}', string)
● Match between n and m occurrences: [Link](r'a{3,5}', string)

7. Flags

● [Link] or re.I - Case-insensitive matching


● [Link] or re.M - Multiline mode, ^ and $ match the start and end
of each line
● [Link] or re.S - Dot matches all characters, including newlines
● [Link] or re.X - Verbose mode, allows comments and whitespace in the
pattern
● [Link] or re.A - ASCII-only matching, ignores locale-specific
characters
● [Link] or re.U - Unicode matching, interprets the pattern as a
Unicode string
● Case-insensitive matching: [Link](r'hello', string, [Link])
● Multiline matching: [Link](r'^hello', string, [Link])
● Dot matches newline: [Link](r'.', string, [Link])

8. Substitution

● [Link](pattern, repl, string) - Replaces all occurrences of the pattern


with the replacement string
● [Link](pattern, repl, string) - Same as [Link](), but also returns the
number of replacements made
● \g<name> - Inserts the text captured by the named group in the
replacement string
● \1, \2, etc. - Inserts the text captured by the corresponding group in
the replacement string

By: Waleed Mousa


● Replace a pattern with a string: [Link](r'hello', 'hi', string)
● Replace a pattern with a function: [Link](r'hello', lambda x:
[Link](0).upper(), string)
● Replace a pattern with a captured group: [Link](r'(hello) (world)', r'\2
\1', string)
● Replace a pattern with a named group: [Link](r'(?P<greeting>hello)
(?P<name>world)', r'\g<name> \g<greeting>', string)

9. Splitting

● [Link](pattern, string) - Splits the string at each occurrence of the


pattern
● [Link](pattern, string, maxsplit) - Splits the string at each
occurrence of the pattern, limiting the number of splits

10. Finding

● [Link](pattern, string) - Searches for the first occurrence of the


pattern in the string
● [Link](pattern, string) - Matches the pattern at the start of the
string
● [Link](pattern, string) - Matches the pattern against the entire
string
● [Link](pattern, string) - Finds all occurrences of the pattern in
the string
● [Link](pattern, string) - Returns an iterator yielding match
objects for all occurrences of the pattern

12. Match Object Methods

● [Link]() or [Link](0) - Returns the entire matched text


● [Link](n) - Returns the text captured by the nth group
● [Link]() - Returns a tuple containing all captured groups
● [Link]() - Returns a dictionary containing named captured
groups
● [Link]() - Returns the start index of the match
● [Link]() - Returns the end index of the match
● [Link]() - Returns a tuple containing the start and end indices of
the match

By: Waleed Mousa


13. Compilation

● Compile a regular expression: pattern = [Link](r'hello')


● Use a compiled pattern for searching: [Link](string)
● Use a compiled pattern for substitution: [Link]('hi', string)

14. Unicode and Raw Strings

● Match Unicode characters: [Link](r'\u0394', string)


● Use raw strings to avoid escaping backslashes: [Link](r'\\', string)

15. Backreferences

● Backreference to a captured group: [Link](r'(hello) world \1', string)


● Named backreference: [Link](r'(?P<greeting>hello) world
(?P=greeting)', string)

16. Conditional Matching

● Conditional matching: [Link](r'(hello)?(?(1) world| universe)',


string)

17. Lookahead and Lookbehind

● Positive lookahead: [Link](r'hello(?= world)', string)


● Negative lookahead: [Link](r'hello(?! world)', string)
● Positive lookbehind: [Link](r'(?<=hello )world', string)
● Negative lookbehind: [Link](r'(?<!hello )world', string)

18. Atomic Grouping

● Atomic grouping: [Link](r'(?>hello|hi) world', string)

19. Possessive Quantifiers

● Possessive quantifier (zero or more): [Link](r'a*+', string)


● Possessive quantifier (one or more): [Link](r'a++', string)
● Possessive quantifier (zero or one): [Link](r'a?+', string)

By: Waleed Mousa


20. Verbose Mode

● Verbose mode (ignore whitespace and comments): [Link](r''' hello #


match hello \s # match whitespace world # match world ''', string,
[Link])

21. Common Patterns


● Email address: r'^[\w\.-]+@[\w\.-]+\.\w+$'
● URL: r'^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$'
● IP address: r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$'
● Date (MM/DD/YYYY): r'^\d{1,2}\/\d{1,2}\/\d{4}$'
● Time (HH:MM:SS): r'^\d{1,2}:\d{1,2}:\d{1,2}$'
● Phone number (US): r'^\(\d{3}\)\s?\d{3}[-\.\s]?\d{4}$'
● Zip code (US): r'^\d{5}(?:[-\s]\d{4})?$'
● Credit card number: r'^\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}$'
● Social Security Number (SSN): r'^\d{3}[-\s]?\d{2}[-\s]?\d{4}$'
● Hexadecimal color code: r'^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$'
● ISBN (10 or 13 digits): r'^(?:\d{9}[\dX]|\d{13})$'
● MD5 hash: r'^[a-fA-F0-9]{32}$'
● SHA1 hash: r'^[a-fA-F0-9]{40}$'
● SHA256 hash: r'^[a-fA-F0-9]{64}$'
● UUID:
r'^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9
]{12}$'
● Strong password:
r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$'
● Username: r'^[a-zA-Z0-9_-]{3,16}$'
● Slug: r'^[a-z0-9]+(?:-[a-z0-9]+)*$'
● File path (Unix): r'^(?:/[^/]+)+$'
● File path (Windows): r'^(?:[a-zA-Z]:)?(?:\\[^\\]+)+$'
● Lowercase letters: r'^[a-z]+$'
● Uppercase letters: r'^[A-Z]+$'
● Alphanumeric characters: r'^[a-zA-Z0-9]+$'
● Digits: r'^\d+$'
● Whitespace characters: r'^\s+$'
● Non-whitespace characters: r'^\S+$'
● Alphabetic characters: r'^[a-zA-Z]+$'
● Hexadecimal digits: r'^[a-fA-F0-9]+$'
● Octal digits: r'^[0-7]+$'

By: Waleed Mousa


● Binary digits: r'^[01]+$'
● Roman numerals (I to M):
r'^(?=[MDCLXVI])M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$'

By: Waleed Mousa

You might also like