Regular Expressions Cheat Sheet

A Programming › Python cheat sheet in English by dogwith4shoes

Basic Regex syntax.

4,377 views 1,522 downloads 15 Nov 2021 History

Syntax

.
Wildcard
^
Start of a string
$
End of a string
x*
0+ repeti­tions of x
x+
1+ repeti­tions of x
x?
0-1 repeti­tions of x
x{m}
m repeti­tions of x
x{m,n}
m-n repeti­tions of x, greedy
x{m,n}?
m-n repeti­tions of x, non-greedy
x|y
x OR y
[^x]
NOT x
\a
Literal '­a'
x*{int}
'­x*' must be int long
< x > < y >
Colloc­ations of x and y
<x> (<y­>)
Only returns y

Whitespace characters

\n
newline
\s
space
\t
tab
\e
escape
\r
return

Functions

search()
Somewhere in string
findall()
Somewhere in the string, non-ov­erl­apping
match()
Beginning of string
fullma­tch()
Entire string
Arguments: pat­tern, string, <fl­­ag­=­0>

Special escape characters

\A
IS at start of string
\b
IS at wordbreak
\B
NOT at wordbreak
\d
IS [0-9]
\D
NOT [0-9]
\s
White space characters
\S
NOT white space characters
\w
IS Unicode word character [a-ZA-­Z0-9_]
\W
NOT Unicode word character
\Z
IS at end of string

.format

'­{:n­}'.f­orm­at(x)
Prints x, padded with n whitespace
{:<n}
Left justified
{:>n}
Right justified
{:.nf}
Show n decimal places
'­{:{­wid­th}­}'.f­orm­at(­'­x', width=n)

Hierarchy

1
Parent­hesis
( )
2
Counters
* + ? { }
3
Sequences and anchors
^ $
4
Disjun­ction
|

Flags

re.I
re.IGN­ORECASE
re.M
re.MUL­TILINE
^ $ match line boundaries
re.X
re.VERBOSE
Ignores whitespace

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.