A regular expression (RegEx) is a pattern used to search, match, validate, extract, or modify text. Python supports them through the built-in re module, where patterns are built from special characters such as \d (digits) and ^ (start of string).
import re
txt = 'Codeexai: A computer science portal for coders'
match = re.search(r'portal', txt)
if match:
print(match.group())
print("Start:", match.start(), "End:", match.end())
else:
print("No match")Output:
portal
Start: 29 End: 35re.search() returns the first occurrence of "portal". group() gives the matched text, and start() and end() give its position in the string (spaces count as characters).
Why Use RegEx?
| Use Case | Description |
|---|---|
| Data mining | Pull emails, phone numbers, URLs, and similar items out of large blocks of text |
| Validation | Check user input such as email addresses, passwords, and dates |
| Text processing | Replace or reformat strings, for example changing a date format |
Metacharacters
Metacharacters carry special meaning in a pattern and are used throughout the functions of the re module.
| Character | Meaning |
|---|---|
\ | Removes the special meaning of the character that follows |
[] | Defines a character class |
^ | Matches the start of the string |
$ | Matches the end of the string |
. | Matches any character except a newline |
| | OR: matches any of the alternatives it separates |
? | Zero or one occurrence |
* | Zero or more occurrences |
+ | One or more occurrences |
{} | Specifies how many times the preceding pattern must occur |
() | Groups part of a pattern |
The group(), start(), and end() methods return matched text and its position.
Special Sequences
Special sequences begin with a backslash and match particular kinds of characters or positions. They shorten complex patterns and make them easier to read.
| Sequence | Description | Example pattern | Matches |
|---|---|---|---|
\A | String starts with the given pattern | \Afor | "for coders", "for the world" |
\b | Word starts or ends with the given pattern. \b(text) checks the start of a word, (text)\b checks the end | \bco | "coders", "code" |
\B | Opposite of \b: the pattern must not be at a word's start or end | \Bco | "decode", "record" |
\d | Any digit; same as [0-9] | \d | "123", "code1" |
\D | Any non-digit; same as [^0-9] | \D | "coders", "code1" |
\s | Any whitespace character | \s | "co ders", "a bc a" |
\S | Any non-whitespace character | \S | "a bd", "abcd" |
\w | Any letter, digit, or underscore; same as [a-zA-Z0-9_] | \w | "123", "CodeS4" |
\W | Any character that is not a letter, digit, or underscore | \W | ">$", "code<>" |
\Z | String ends with the given pattern | ab\Z | "abcdab", "abababab" |
Basic Patterns
1. Character Classes
A character class, written in square brackets, matches any one character from a set.
import re
print(re.findall(r'[Cc]odeexai', 'Codeexai: A computer science portal for codeexai'))Output:
['Codeexai', 'codeexai']2. Ranges
Inside brackets, a hyphen defines a span of characters. [0-9] matches digits and [A-Z] matches uppercase letters.
import re
print('Range', re.search(r'[a-zA-Z]', 'x'))Output:
Range <re.Match object; span=(0, 1), match='x'>3. Negation
A ^ placed first inside the brackets matches anything except the listed characters.
Syntax:
[^a-z]import re
print(re.search(r'[^a-z]', 'c'))
print(re.search(r'C[^o]', 'Codeexai'))Output:
None
None4. Shortcuts
Shortcuts are shorthand for common character classes:
\w: a word character\d: a digit\s: whitespace (space, tab, newline, etc.)\b: a word boundary (a zero-width position, not a character)
import re
print('Code:', re.search(r'\bCode\b', 'Code'))
print('Codeexai:', re.search(r'\bCode\b', 'Codeexai'))Output:
Code: <re.Match object; span=(0, 4), match='Code'>
Codeexai: None5. Start and End of a String
^ anchors a match to the start of the string, and $ anchors it to the end.
import re
# Start of string
match = re.search(r'^Codeexai', 'Campus Codeexai of the month')
print('Beg. of String:', match)
match = re.search(r'^Codeexai', 'Codeexai of the month')
print('Beg. of String:', match)
# End of string
match = re.search(r'Codeexai$', 'Compute science portal-Codeexai')
print('End of String:', match)Output:
Beg. of String: None
Beg. of String: <re.Match object; span=(0, 8), match='Codeexai'>
End of String: <re.Match object; span=(23, 31), match='Codeexai'>6. Any Character
Outside of brackets, . stands for any single character.
import re
print('Any Character', re.search(r'p.th.n', 'python 3'))Output:
Any Character <re.Match object; span=(0, 6), match='python'>7. Optional Characters
Adding ? makes the preceding character or class appear either once or not at all. This handles alternate spellings such as "color" and "colour".
import re
print('Color', re.search(r'colou?r', 'color'))
print('Colour', re.search(r'colou?r', 'colour'))Output:
Color <re.Match object; span=(0, 5), match='color'>
Colour <re.Match object; span=(0, 6), match='colour'>8. Repetition
Repetition matches the same character or class several times. The pattern below detects a date in dd-mm-yyyy format.
import re
print('Date{dd-mm-yyyy}:', re.search(r'[\d]{2}-[\d]{2}-[\d]{4}',
'18-08-2020'))Output:
Date{dd-mm-yyyy}: <re.Match object; span=(0, 10), match='18-08-2020'>The engine checks for two digits, then a hyphen, then two more digits, another hyphen, and finally four digits.
Repetition ranges
A range accepts several lengths. This pattern allows three or four digits:
import re
print('Three Digit:', re.search(r'[\d]{3,4}', '189'))
print('Four Digit:', re.search(r'[\d]{3,4}', '2145'))Output:
Three Digit: <re.Match object; span=(0, 3), match='189'>
Four Digit: <re.Match object; span=(0, 4), match='2145'>Open-ended ranges
When there is no upper limit, leave the maximum blank. This is useful for something like a street address:
import re
print(re.search(r'[\d]{1,}', '5th Floor, A-118,\
Sector-136, Noida, Uttar Pradesh - 201305'))Output:
<re.Match object; span=(0, 1), match='5'>Shorthand
+ means one or more ({1,}) and * means zero or more ({0,}).
import re
print(re.search(r'[\d]+', '5th Floor, A-118,\
Sector-136, Noida, Uttar Pradesh - 201305'))Output:
<re.Match object; span=(0, 1), match='5'>9. Grouping
Parentheses split a pattern into groups so each matched part can be retrieved separately.
import re
grp = re.search(r'([\d]{2})-([\d]{2})-([\d]{4})', '26-08-2020')
print(grp)Output:
<re.Match object; span=(0, 10), match='26-08-2020'>Entire match: group() returns the whole matched text.
import re
grp = re.search(r'([\d]{2})-([\d]{2})-([\d]{4})', '26-08-2020')
print(grp.group())Output:
26-08-2020Tuple of groups: groups() returns every group as a tuple.
import re
grp = re.search(r'([\d]{2})-([\d]{2})-([\d]{4})', '26-08-2020')
print(grp.groups())Output:
('26', '08', '2020')Single group: pass an index to group().
import re
grp = re.search(r'([\d]{2})-([\d]{2})-([\d]{4})', '26-08-2020')
print(grp.group(3))Output:
2020Named groups: use the (?P<name>...) syntax to label groups.
import re
match = re.search(r'(?P<dd>[\d]{2})-(?P<mm>[\d]{2})-(?P<yyyy>[\d]{4})',
'26-08-2020')
print(match.group('mm'))Output:
08Groups as a dictionary: groupdict() returns the named groups as a dictionary, with group names as keys.
import re
match = re.search(r'(?P<dd>[\d]{2})-(?P<mm>[\d]{2})-(?P<yyyy>[\d]{4})',
'26-08-2020')
print(match.groupdict())Output:
{'dd': '26', 'mm': '08', 'yyyy': '2020'}10. Lookahead
A negated character class needs an actual character to test, so it fails when the match sits at the end of the string. Lookahead avoids this by accepting or rejecting a match based on what follows, without consuming it.
import re
print('negation:', re.search(r'n[^e]', 'Python'))
print('lookahead:', re.search(r'n(?!e)', 'Python'))Output:
negation: None
lookahead: <re.Match object; span=(5, 6), match='n'>This is a negative lookahead ((?!...)): it succeeds only if the given character does not follow. Replacing ! with = gives a positive lookahead, which succeeds only if the character does follow.
import re
print('positive lookahead', re.search(r'n(?=e)', 'jasmine'))Output:
positive lookahead <re.Match object; span=(5, 6), match='n'>11. Substitution
re.sub() replaces matched text and returns the new string. It is handy for stripping characters such as /, -, or . before saving data to a database. It takes three arguments:
- The regular expression
- The replacement string
- The string to search
The example below removes the hyphens from a credit card number.
import re
print(re.sub(r'([\d]{4})-([\d]{4})-([\d]{4})-([\d]{4})', r'\1\2\3\4',
'1111-2222-3333-4444'))Output:
1111222233334444Compiled Regular Expressions
re.compile() turns a pattern into a RegEx object that can be reused for search, match, sub, and other operations.
import re
regex = re.compile(r'([\d]{2})-([\d]{2})-([\d]{4})')
# search method
print('compiled reg expr', regex.search('26-08-2020'))
# sub method
print(regex.sub(r'\1.\2.\3', '26-08-2020'))Output:
compiled reg expr <re.Match object; span=(0, 10), match='26-08-2020'>
26.08.2020re.compile() builds a reusable pattern for dates in DD-MM-YYYY format. regex.search() finds the date, and regex.sub(r'\1.\2.\3', ...) converts 26-08-2020 to 26.08.2020.