Regular Expressions
Regular Expressions (regex) are a powerful mini-language for describing and matching patterns within text - used constantly in data cleaning to validate, extract, or transform messy, unstructured text data.
Basic Pattern Matching
import re
text = "Contact us at support@uncodemy.com"
match = re.search(r"\w+@\w+\.\w+", text)
if match:
print(match.group()) # support@uncodemy.com
Common Regex Functions
re.search()- finds the first match anywhere in the stringre.match()- checks for a match only at the beginning of the stringre.findall()- returns a list of all matches found in the stringre.sub()- replaces matched patterns with a new value
import re
text = "Call 9876543210 or 9123456780 for support"
numbers = re.findall(r"\d{10}", text)
print(numbers) # ['9876543210', '9123456780']
cleaned = re.sub(r"\d{10}", "[REDACTED]", text)
print(cleaned) # Call [REDACTED] or [REDACTED] for support
Common Pattern Symbols
\d- any digit,\w- any word character,\s- any whitespace*- zero or more,+- one or more,?- zero or one^- start of string,$- end of string
Regular expressions can get complex quickly - when writing a non-trivial pattern, testing it on a tool like an online regex tester before dropping it into your code can save significant debugging time.
Coming Up Next
To close out this module, the final topic takes a deeper, more complete look at Exception Handling in Python.