Regular Expression Examples in Python


Literal characters

Sr.No.Example & Description
1python
Matches beginning of line.

Character classes

Sr.No.Example & Description
1[Pp]ython
Match "Python" or "python"
2rub[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

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: [ \t\r\n\f]
5\S
Match nonwhitespace: [^ \t\r\n\f]
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
1ruby?
Match "rub" or "ruby": the y is optional
2ruby*
Match "rub" plus 0 or more ys
3ruby+
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\D\d+
No group: + repeats \d
2(\D\d)+
Grouped: + repeats \D\d 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

Sr.No.Example & Description
1python|perl
Match "python" or "perl"
2rub(y|le))
Match "ruby" or "ruble"
3Python(!+|\?)
"Python" followed by one or more ! or one ?

Anchors

This needs to specify match position.

Sr.No.Example & Description
1^Python
Match "Python" at the start of a string or internal line
2Python$
Match "Python" at the end of a string or line
3\APython
Match "Python" at the start of a string
4Python\Z
Match "Python" at the end of a string
5\bPython\b
Match "Python" at a word boundary
6\brub\B
\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
7Python(?=!)
Match "Python", if followed by an exclamation point.
8Python(?!!)
Match "Python", if not followed by an exclamation point.

Updated on: 31-Jan-2020

232 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements