Loading lessons...
RegEx
RegEx
A regular expression (regex) is a pattern for searching text. Python provides the re module.
Import and search
import re
txt = "The rain in Spain"
x = re.search("^The.*Spainquot;, txt)
The search function
re.search() scans the whole string for a match and returns a match object (or None):
x = re.search("ai", txt)
print(x) # <re.Match object...>
Common functions
findall(): returns a list of all matches.search(): returns the first match as an object.split(): splits the string at matches.sub(): replaces matches.
print(re.findall("ai", txt)) # ['ai', 'ai']
print(re.split("\s", txt)) # split on whitespace
print(re.sub("Spain", "France", txt))# The rain in France
Metacharacters
| Char | Meaning | |
|---|---|---|
[] | A set of characters | |
. | Any character | |
^ | Starts with | |
$ | Ends with | |
* | Zero or more | |
+ | One or more | |
? | Zero or one | |
{} | Exactly the given number | |
| ` | ` | Either or |
() | Capture and group |
Example with a set
print(re.findall("[a-m]", txt)) # letters a through m
Special sequences
\d: digits.\s: whitespace.\w: word characters.\b: word boundary.
TL;DR
- Regex patterns search text with the re module.
- findall, search, split, sub are the main functions.
- Metacharacters shape the pattern.
- Use raw strings (r"...") to avoid escape confusion.