Python Regex Cheatsheet With Examples: Re Module Functions
Python Regex Cheatsheet With Examples: Re Module Functions
A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern. They’re
typically used to find a sequence of characters within a string so you can extract and manipulate them.
For example, the following returns both instances of ‘active’:
import re
pattern = 'ac..ve'
test_string = 'my activestate platform account is now active'
result = re.findall(pattern, test_string)
RegExes are extremely useful, but the syntax can be hard to recall. With that in mind, ActiveState offers
this “cheatsheet” to help point you in the right direction when building RegExes in Python.
+
match 1 or more occurrences (?<=B)A match expression A only if it follows B
(eg., py+) match expression A only if not preceded by
?
match 0 or 1 occurrences (?<!B)A B
(eg., py?)
(?aiLmsux) where a, i, L, m, s, u, and x are flags:
match exactly m occurrences
{m} (eg., py{3}) a = match ASCII only
i = make matches ignore case
match from m to n occurrences
{m,n} (eg., py{1,3}) L = make matches locale dependent
m = multi-line makes ^ and $ match at the
match from 0 to n occurrences
{,n} (eg., py{,3}) beginning/end of each line, respectively
re Module Functions
Besides enabling the above functionality, the ‘re’ module also features a number of popular functions: