How to use regular expressions in Python
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
In Python, you can use regular expressions (regex) with the re
module.
Here are some basic regex operations in Python:
search
: Searches the string for a match to the regex pattern and returns aMatch
object if there is a match anywhere in the string.
import re
text = "The cat is cute."
match = re.search(r"cat", text)
if match:
print("Match found!")
findall
: Returns a list containing all matches in the string as strings.
import re
text = "The cat is cute. The dog is friendly."
matches = re.findall(r"\w+", text)
print(matches)
# Output: ['The', 'cat', 'is', 'cute', 'The', 'dog', 'is', 'friendly']
sub
: Replaces all occurrences of the regex pattern in the string with a specified replacement.
import re
text = "The cat is cute. The dog is friendly."
new_text = re.sub(r"\bcat\b", "dog", text)
print(new_text)
# Output: 'The dog is cute. The dog is friendly.'
split
: Splits the string by the occurrences of the regex pattern.
import re
text = "The cat is cute. The dog is friendly."
words = re.split(r"\s+", text)
print(words)
# Output: ['The', 'cat', 'is', 'cute.', 'The', 'dog', 'is', 'friendly.']
These are just some of the basic operations you can perform with regex in Python. You can find more information in the Python documentation: https://docs.python.org/3/library/re.html
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months π
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons β Approach used by real data scientist. Not bookworms. π