10 Mar Python Regular Expressions
Python’s re module allows you to search, match, split, and replace text using Regular Expressions (RegEx). It’s powerful for pattern-matching tasks like validating emails, extracting substrings, or replacing text. Below are clear examples with code snippets to help you practice.
Basics of Python RegEx
- Import module: import re
- Common functions:
- re.match() → Checks for a match at the beginning of a string.
- re.search() → Searches for a match anywhere in the string.
- re.findall() → Returns all matches as a list.
- re.split() → Splits string by pattern.
- re.sub() → Replaces matches with new text.
RegEx Examples
Let us see some Regular Expression examples in Python:
- Match at Start
- Search Anywhere
- Find All Matches
- Split by Pattern
- Replace Text
Let’s start with the examples:
Match at Start using the match() function
Check for a match at the beginning of a string using the match() function:
import re
pattern = '^c......t$'
txt = 'crickett'
result = re.match(pattern, txt)
if result:
print("Search is successful.")
else:
print("Search is unsuccessful.")
Output
Search is successful.
Search Anywhere using the search() function
Search for a match anywhere in the string using the search() method:
import re
txt = "The Cricket World Cup"
res = re.search("^The.*Cup", txt)
print("Pattern found!" if res else "Not found")
Output
Pattern found!
Find All Matches using the findall() function
To find and return all matches as a list, use the findall() function in Python:
import re txt = "sun fun run" matches = re.findall(r"[sf]un", txt) print(matches)
Output
['sun', 'fun']
Split by Pattern using the split() function
To split a string by a pattern, use the split() function in Python:
import re txt = "cricket, football; archery tennis" res = re.split(r"[;,\s]\s*", txt) print(res)
Output
['cricket', 'football', 'archery', 'tennis']
Replace Text using the sub() function
To replace matches with new text, use the sub() function in Python:
import re txt = "T20 World Cup" res = re.sub(r"T20", "ODI", txt) print(res)
Output
ODI World Cup
We replaced T20 with ODI in the above example.
If you liked the tutorial, spread the word and share the link and our website, Studyopedia, with others.
For Videos, Join Our YouTube Channel: Join Now
Read More:
No Comments