Regular Expressions, commonly called Regex, are patterns used to search, match, and manipulate text.
Python provides the built-in re module for working with regular expressions.
A regular expression is a sequence of characters that defines a search pattern.
For example, the pattern cat can be used to search for the word "cat".
import re
text = "The cat is sleeping."
result = re.search("cat", text)
print(result)
<re.Match object ...>
Python's regular expression functionality is provided by the built-in re module.
import re
After importing the module, you can use functions such as:
re.search()re.match()re.findall()re.finditer()re.sub()re.split()re.fullmatch()
The re.search() function searches the entire string for the first location where the pattern matches.
import re
text = "I am learning Python."
result = re.search("Python", text)
if result:
print("Pattern found")
Pattern found
The re.match() function checks for a match at the beginning of the string.
import re
text = "Python is easy."
result = re.match("Python", text)
if result:
print("Match found")
Match found
If the pattern does not occur at the beginning, re.match() returns None.
The re.fullmatch() function succeeds only when the entire string matches the pattern.
import re
text = "Python"
result = re.fullmatch("Python", text)
if result:
print("Full match")
Full match
The re.findall() function returns all non-overlapping matches as a list.
import re
text = "Python is easy. Python is powerful."
result = re.findall("Python", text)
print(result)
['Python', 'Python']
The re.finditer() function returns an iterator containing match objects.
import re
text = "Python is easy. Python is powerful."
matches = re.finditer("Python", text)
for match in matches:
print(match.group())
Python Python
The re.sub() function replaces matches with another string.
import re
text = "I like Java."
new_text = re.sub("Java", "Python", text)
print(new_text)
I like Python.
The re.split() function splits a string wherever the pattern matches.
import re
text = "apple,banana,orange"
result = re.split(",", text)
print(result)
['apple', 'banana', 'orange']
Character classes allow you to match specific types or groups of characters.
| Pattern | Meaning |
|---|---|
[abc] |
Matches a, b, or c |
[^abc] |
Matches a character other than a, b, or c |
[a-z] |
Matches lowercase letters from a to z |
[A-Z] |
Matches uppercase letters from A to Z |
[0-9] |
Matches a digit from 0 to 9 |
The \d pattern matches a Unicode decimal digit by default.
import re
text = "My age is 25."
result = re.findall(r"\d", text)
print(result)
['2', '5']
The + quantifier means one or more occurrences.
import re
text = "My age is 25 and my pin is 1234."
result = re.findall(r"\d+", text)
print(result)
['25', '1234']
The \w pattern matches Unicode word characters by default, including letters, digits, and underscore.
import re
text = "Python_123"
result = re.findall(r"\w", text)
print(result)
['P', 'y', 't', 'h', 'o', 'n', '_', '1', '2', '3']
The \s pattern matches whitespace characters such as spaces and line breaks.
import re
text = "Hello World"
result = re.findall(r"\s", text)
print(result)
[' ']
The dot . matches almost any character except a newline by default.
import re
text = "cat"
result = re.findall(r".", text)
print(result)
['c', 'a', 't']
The ^ symbol matches the beginning of a string, while $ matches the end.
import re
text = "Python"
result = re.search(r"^Python$", text)
if result:
print("Exact match")
Exact match
Quantifiers specify how many times a pattern can occur.
| Quantifier | Meaning |
|---|---|
* |
Zero or more |
+ |
One or more |
? |
Zero or one |
{n} |
Exactly n times |
{n,} |
At least n times |
{n,m} |
Between n and m times |
import re
text = "I have 123 apples."
result = re.findall(r"\d+", text)
print(result)
['123']
The + combines consecutive matching digits into one match.
import re
text = "color colour"
result = re.findall(r"colou*r", text)
print(result)
['color', 'colour']
The * allows the character before it to occur zero or more times.
import re
text = "color colour"
result = re.findall(r"colou?r", text)
print(result)
['color', 'colour']
The ? means that the preceding character or group is optional and may occur zero or one time.
Parentheses () are used to create groups in regular expressions.
import re
text = "My phone is 9876543210"
result = re.search(r"(\d{10})", text)
if result:
print(result.group(1))
9876543210
import re
text = "Name: Rahul, Age: 25"
pattern = r"Name: (\w+), Age: (\d+)"
result = re.search(pattern, text)
if result:
print(result.group(1))
print(result.group(2))
Rahul 25
The | symbol means "or".
import re
text = "I like Python"
result = re.search(r"Python|Java", text)
if result:
print(result.group())
Python
Raw strings are commonly used when writing regular expressions because backslashes do not need to be escaped in the same way as ordinary Python strings.
pattern = r"\d+"
print(pattern)
\d+
Using r"..." makes regex patterns easier to read, especially when they contain many backslashes.
import re
text = "Contact us at hello@example.com"
pattern = r"[\w.-]+@[\w.-]+\.\w+"
result = re.search(pattern, text)
if result:
print(result.group())
hello@example.com
import re
text = "Call me at 9876543210"
pattern = r"\b\d{10}\b"
result = re.search(pattern, text)
if result:
print(result.group())
9876543210
The re.IGNORECASE flag can be used when uppercase and lowercase differences should be ignored.
import re
text = "Python is powerful."
result = re.search("python", text, re.IGNORECASE)
if result:
print("Found")
Found
The re.compile() function creates a compiled regular expression pattern that can be reused.
import re
pattern = re.compile(r"\d+")
text = "Age 25, PIN 1234"
result = pattern.findall(text)
print(result)
['25', '1234']
| Pattern | Meaning |
|---|---|
\d |
Digit |
\w |
Word character |
\s |
Whitespace |
. |
Any character except newline by default |
^ |
Beginning of string |
$ |
End of string |
* |
Zero or more |
+ |
One or more |
? |
Zero or one |
| |
OR |
() |
Group |
[] |
Character class |
re module.re.search() searches for a pattern anywhere in the string.re.match() checks for a match at the beginning.re.fullmatch() requires the entire string to match.re.findall() returns all non-overlapping matches.re.sub() replaces matching text.re.split() splits text using a regular expression.*, +, and ? control repetition.\d, \w, and \s simplify pattern matching.Question: Which Python module is used for regular expressions?