Python 3 - Regular Expressions - A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pat. .NET, Java, Python 3, Ruby: position where one side only is a Unicode letter, digit or underscore. Unlike lots of other cheat sheets or regex web sites, I was. Regex Cheat Sheet The original cheat sheet can be found here https. Python 3, Ruby: position where one side only is a Unicode letter, digit or underscore. Real Python: Python 3 Cheat Sheet. Contents 1 Introduction 2. Python is a beautiful language. It’s easy to learn and fun, and its syntax is simple yet ele.
By Alex Yang, Dataquest
This cheat sheet is based on Python 3’s documentation on regular expressions. If you're interested in learning Python, we have a free Python Programming: Beginner course for you to try out.
Download the cheat sheet here
Special Characters
^
| Matches the expression to its right at the start of a string. It matches every such instance before each n
in the string.
$
| Matches the expression to its left at the end of a string. It matches every such instance before each n
in the string.
.
| Matches any character except line terminators like n
.
| Escapes special characters or denotes character classes.
A|B
| Matches expression A
or B
. If A
is matched first, B
is left untried.
+
| Greedily matches the expression to its left 1 or more times.
*
| Greedily matches the expression to its left 0 or more times.
?
| Greedily matches the expression to its left 0 or 1 times. But if ?
is added to qualifiers (+
, *
, and ?
itself) it will perform matches in a non-greedy manner.
{m}
| Matches the expression to its left m
times, and not less.
{m,n}
| Matches the expression to its left m
to n
times, and not less.
{m,n}?
| Matches the expression to its left m
times, and ignores n
. See ?
above.
Character Classes (a.k.a. Special Sequences)
w
| Matches alphanumeric characters, which means a-z
, A-Z
, and 0-9
. It also matches the underscore, _
.
d
| Matches digits, which means 0-9
.
D
| Matches any non-digits.
s
| Matches whitespace characters, which include the t
, n
, r
, and space characters.
S
| Matches non-whitespace characters.
b
| Matches the boundary (or empty string) at the start and end of a word, that is, between w
and W
.
B
| Matches where b
does not, that is, the boundary of w
characters.
A
| Matches the expression to its right at the absolute start of a string whether in single or multi-line mode.
Z
| Matches the expression to its left at the absolute end of a string whether in single or multi-line mode.
Sets
[ ]
| Contains a set of characters to match.
[amk]
| Matches either a
, m
, or k
. It does not match amk
.
[a-z]
| Matches any alphabet from a
to z
.
[a-z]
| Matches a
, -
, or z
. It matches -
because escapes it.
[a-]
| Matches a
or -
, because -
is not being used to indicate a series of characters.
[-a]
| As above, matches a
or -
.
[a-z0-9]
| Matches characters from a
to z
and also from 0
to 9
.
[(+*)]
| Special characters become literal inside a set, so this matches (
, +
, *
, and )
.
[^ab5]
| Adding ^
excludes any character in the set. Here, it matches characters that are not a
, b
, or 5
.
Groups
( )
| Matches the expression inside the parentheses and groups it.
(? )
| Inside parentheses like this, ?
acts as an extension notation. Its meaning depends on the character immediately to its right.
(?PAB)
| Matches the expression AB
, and it can be accessed with the group name.
(?aiLmsux)
| Here, a
, i
, L
, m
, s
, u
, and x
are flags:
a
— Matches ASCII onlyi
— Ignore caseL
— Locale dependentm
— Multi-lines
— Matches allu
— Matches unicodex
— Verbose
(?:A)
| Matches the expression as represented by A
, but unlike (?PAB)
, it cannot be retrieved afterwards.
(?#..)
| A comment. Contents are for us to read, not for matching.
A(?=B)
| Lookahead assertion. This matches the expression A
only if it is followed by B
.
A(?!B)
| Negative lookahead assertion. This matches the expression A
only if it is not followed by B
.
(?<=B)A
| Positive lookbehind assertion. This matches the expression A
only if B
is immediately to its left. This can only matched fixed length expressions.
(?<!B)A
| Negative lookbehind assertion. This matches the expression A
only if B
is not immediately to its left. This can only matched fixed length expressions.
(?P=name)
| Matches the expression matched by an earlier group named “name”.
(..)1
| The number 1
corresponds to the first group to be matched. If we want to match more instances of the same expresion, simply use its number instead of writing out the whole expression again. We can use from 1
up to 99
such groups and their corresponding numbers.
Popular Python re module Functions
re.findall(A, B)
| Matches all instances of an expression A
in a string B
and returns them in a list.
re.search(A, B)
| Matches the first instance of an expression A
in a string B
, and returns it as a re match object.
re.split(A, B)
| Split a string B into a list using the delimiter A
.
re.sub(A, B, C)
| Replace A
with B
in the string C
.
Useful Regular Expressions Sites for Python users
Bio: Alex Yang is a writer fascinated by the things code can do. He also enjoys citizen science and new media art.
Original. Reposted with permission.
Related:
- Python 3 Basic Tutorial
- Python 3 Advanced Tutorial
- Python 3 Useful Resources
- Selected Reading
A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.
The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression.
We would cover two important functions, which would be used to handle regular expressions. Nevertheless, a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'.
Basic patterns that match single chars
Sr.No. | Expression & Matches |
---|---|
1 | a, X, 9, < ordinary characters just match themselves exactly. |
2 | . (a period) matches any single character except newline 'n' |
3 | w matches a 'word' character: a letter or digit or underbar [a-zA-Z0-9_]. |
4 | W matches any non-word character. |
5 | b boundary between word and non-word |
6 | s matches a single whitespace character -- space, newline, return, tab |
7 | S matches any non-whitespace character. |
8 | t, n, r tab, newline, return |
9 | d decimal digit [0-9] |
10 | ^ matches start of the string |
11 | $ match the end of the string |
12 | inhibit the 'specialness' of a character. |
Compilation flags
Compilation flags let you modify some aspects of how regular expressions work. Flags are available in the re module under two names, a long name such as IGNORECASE and a short, one-letter form such as I.
Sr.No. | Flag & Meaning |
---|---|
1 | ASCII, A Makes several escapes like w, b, s and d match only on ASCII characters with the respective property. |
2 | DOTALL, S Make, match any character, including newlines |
3 | IGNORECASE, I Do case-insensitive matches |
4 | LOCALE, L Do a locale-aware match |
5 | MULTILINE, M Multi-line matching, affecting ^ and $ |
6 | VERBOSE, X (for ‘extended’) Enable verbose REs, which can be organized more cleanly and understandably |
The match Function
This function attempts to match RE pattern to string with optional flags.
Here is the syntax for this function −
Here is the description of the parameters −
Sr.No. | Parameter & Description |
---|---|
1 | pattern This is the regular expression to be matched. |
2 | string This is the string, which would be searched to match the pattern at the beginning of string. |
3 | flags You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below. |
The re.match function returns a match object on success, None on failure. We usegroup(num) or groups() function of match object to get matched expression.
Sr.No. | Match Object Method & Description |
---|---|
1 | group(num = 0) This method returns entire match (or specific subgroup num) |
2 | groups() This method returns all matching subgroups in a tuple (empty if there weren't any) |
Example
Python 3.8 Cheat Sheet
When the above code is executed, it produces the following result −
The search Function
This function searches for first occurrence of RE pattern within string with optional flags.
Python 3 Cheat Sheet Pdf
Here is the syntax for this function −
Here is the description of the parameters −
Sr.No. | Parameter & Description |
---|---|
1 | pattern This is the regular expression to be matched. |
2 | string This is the string, which would be searched to match the pattern anywhere in the string. |
3 | flags You can specify different flags using bitwise OR (|). These are modifiers, which are listed in the table below. |
The re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get the matched expression.
Sr.No. | Match Object Method & Description |
---|---|
1 | group(num = 0) This method returns entire match (or specific subgroup num) |
2 | groups() This method returns all matching subgroups in a tuple (empty if there weren't any) |
Example
When the above code is executed, it produces the following result −
Matching Versus Searching
Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).
Example
When the above code is executed, it produces the following result −
Search and Replace
One of the most important re methods that use regular expressions is sub.
Syntax
This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max is provided. This method returns modified string.
Example
When the above code is executed, it produces the following result −
Regular Expression Modifiers: Option Flags
Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these −
Sr.No. | Modifier & Description |
---|---|
1 | re.I Performs case-insensitive matching. |
2 | re.L Interprets words according to the current locale. This interpretation affects the alphabetic group (w and W), as well as word boundary behavior (b and B). |
3 | re.M Makes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string). |
4 | re.S Makes a period (dot) match any character, including a newline. |
5 | re.U Interprets letters according to the Unicode character set. This flag affects the behavior of w, W, b, B. |
6 | re.X Permits 'cuter' regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker. |
Regular Expression Patterns
Except for the control characters, (+ ? . * ^ $ ( ) [ ] { } | ), all characters match themselves. You can escape a control character by preceding it with a backslash.
The following table lists the regular expression syntax that is available in Python −
Sr.No. | Parameter & Description |
---|---|
1 | ^ Matches beginning of line. |
2 | $ Matches end of line. |
3 | . Matches any single character except newline. Using m option allows it to match newline as well. |
4 | [..] Matches any single character in brackets. |
5 | [^..] Matches any single character not in brackets |
6 | re* Matches 0 or more occurrences of preceding expression. |
7 | re+ Matches 1 or more occurrence of preceding expression. |
8 | re? Matches 0 or 1 occurrence of preceding expression. |
9 | re{ n} Matches exactly n number of occurrences of preceding expression. |
10 | re{ n,} Matches n or more occurrences of preceding expression. |
11 | re{ n, m} Matches at least n and at most m occurrences of preceding expression. |
12 | a|b Matches either a or b. |
13 | (re) Groups regular expressions and remembers matched text. |
14 | (?imx) Temporarily toggles on i, m, or x options within a regular expression. If in parentheses, only that area is affected. |
15 | (?-imx) Temporarily toggles off i, m, or x options within a regular expression. If in parentheses, only that area is affected. |
16 | (?: re) Groups regular expressions without remembering matched text. |
17 | (?imx: re) Temporarily toggles on i, m, or x options within parentheses. |
18 | (?-imx: re) Temporarily toggles off i, m, or x options within parentheses. |
19 | (?#..) Comment. |
20 | (?= re) Specifies position using a pattern. Does not have a range. |
21 | (?! re) Specifies position using pattern negation. Does not have a range. |
22 | (?> re) Matches independent pattern without backtracking. |
23 | w Matches word characters. |
24 | W Matches nonword characters. |
25 | s Matches whitespace. Equivalent to [tnrf]. |
26 | S Matches nonwhitespace. |
27 | d Matches digits. Equivalent to [0-9]. |
28 | D Matches nondigits. |
29 | A Matches beginning of string. |
30 | Z Matches end of string. If a newline exists, it matches just before newline. |
31 | z Matches end of string. |
32 | G Matches point where last match finished. |
33 | b Matches word boundaries when outside brackets. Matches backspace (0x08) when inside brackets. |
34 | B Matches non-word boundaries. |
35 | n, t, etc. Matches newlines, carriage returns, tabs, etc. |
36 | 1..9 Matches nth grouped subexpression. |
37 | 10 Matches nth grouped subexpression if it matched already. Otherwise refers to the octal representation of a character code. |
Regular Expression Examples
Literal characters
Sr.No. | Example & Description |
---|---|
1 | python Match 'python'. |
Character classes
Sr.No. | Example & Description |
---|---|
1 | [Pp]ython Match 'Python' or 'python' |
2 | rub[ye] Match 'ruby' or 'rube' |
3 | [aeiou] Match any one lowercase vowel |
4 | [0-9] Match any digit; same as [0123456789] |
5 | [a-z] Match any lowercase ASCII letter |
6 | [A-Z] Match any uppercase ASCII letter |
7 | [a-zA-Z0-9] Match any of the above |
8 | [^aeiou] Match anything other than a lowercase vowel |
9 | [^0-9] Match anything other than a digit Free pdf converter for windows 10. |
Special Character Classes
Sr.No. | Example & Description |
---|---|
1 | . Match any character except newline |
2 | d Match a digit: [0-9] |
3 | D Match a nondigit: [^0-9] |
4 | s Match a whitespace character: [ trnf] |
5 | S Match nonwhitespace: [^ trnf] |
6 | w Match a single word character: [A-Za-z0-9_] |
7 | W Match a nonword character: [^A-Za-z0-9_] |
Repetition Cases
Sr.No. | Example & Description |
---|---|
1 | ruby? Match 'rub' or 'ruby': the y is optional |
2 | ruby* Match 'rub' plus 0 or more ys |
3 | ruby+ Match 'rub' plus 1 or more ys |
4 | d{3} Match exactly 3 digits |
5 | d{3,} Match 3 or more digits |
6 | d{3,5} Match 3, 4, or 5 digits |
Nongreedy repetition
This matches the smallest number of repetitions −
Sr.No. | Example & Description |
---|---|
1 | <.*> Greedy repetition: matches '<python>perl>' |
2 | <.*?> Nongreedy: matches '<python>' in '<python>perl>' |
Grouping with Parentheses
Sr.No. | Example & Description |
---|---|
1 | Dd+ No group: + repeats d |
2 | (Dd)+ Grouped: + repeats Dd pair |
3 | ([Pp]ython(,)?)+ Match 'Python', 'Python, python, python', etc. |
Backreferences
This matches a previously matched group again −
Sr.No. | Example & Description |
---|---|
1 | ([Pp])ython&1ails Match python&pails or Python&Pails |
2 | (['])[^1]*1 Single or double-quoted string. 1 matches whatever the 1st group matched. 2 matches whatever the 2nd group matched, etc. |
Alternatives
Python 3.7 Cheat Sheet
Sr.No. | Example & Description |
---|---|
1 | python|perl Match 'python' or 'perl' |
2 | rub(y|le) Match 'ruby' or 'ruble' |
3 | Python(!+|?) 'Python' followed by one or more ! or one ? |
Anchors
Python 3 Regex Cheat Sheet Pdf
This needs to specify match position.
Python 3 Regex Cheat Sheet
Sr.No. | Example & Description |
---|---|
1 | ^Python Match 'Python' at the start of a string or internal line |
2 | Python$ Match 'Python' at the end of a string or line |
3 | APython Match 'Python' at the start of a string |
4 | PythonZ Match 'Python' at the end of a string |
5 | bPythonb Match 'Python' at a word boundary |
6 | brubB B is nonword boundary: match 'rub' in 'rube' and 'ruby' but not alone |
7 | Python(?=!) Match 'Python', if followed by an exclamation point. |
8 | Python(?!!) Match 'Python', if not followed by an exclamation point. |
Special Syntax with Parentheses
Python 3 Regex Cheat Sheet Answers
Sr.No. | Example & Description |
---|---|
1 | R(?#comment) Matches 'R'. All the rest is a comment |
2 | R(?i)uby Case-insensitive while matching 'uby' |
3 | R(?i:uby) Same as above |
4 | rub(?:y|le)) Group only without creating 1 backreference |