Regular expressions (regex) in Python allow you to search, match, and manipulate text based on patterns. They are powerful for string validation, data extraction, and text processing.
Python provides the re module to work with regex:
import re
Why Regular Expressions Are Important
- Validate input (emails, phone numbers, passwords)
- Search and extract data from text
- Replace or format strings efficiently
- Essential in real-world applications like web scraping, log parsing, and data cleaning
Example 1: Basic Matching
import re
pattern = r"\d+" # Matches one or more digits
text = "There are 15 apples and 20 oranges."
matches = re.findall(pattern, text)
print(matches) # Output: ['15', '20']
Example 2: Validating an Email Address
import re
email = "example@gmail.com"
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
if re.match(pattern, email):
print("Valid email")
else:
print("Invalid email")
- Useful for user input validation in real-world applications
Example 3: Replacing Text Using Regex
import re
text = "Contact us at support@example.com"
new_text = re.sub(r"\S+@\S+", "[email protected]", text)
print(new_text) # Output: Contact us at [email protected]
- Allows masking sensitive data in logs or reports
Example 4: Real-World Scenario – Extracting Phone Numbers
import re
text = "Call me at 123-456-7890 or 987-654-3210"
pattern = r"\d{3}-\d{3}-\d{4}"
phones = re.findall(pattern, text)
print(phones) # Output: ['123-456-7890', '987-654-3210']
- Useful for data extraction from documents, emails, or websites
Best Practices
✔ Compile regex patterns using re.compile() for performance
✔ Keep patterns readable and documented
✔ Test regex using online tools or Python console
✔ Avoid overly complex patterns to maintain clarity
Conclusion
Python regular expressions are a powerful tool for text processing. Mastering regex allows you to validate, extract, and manipulate textual data efficiently, which is crucial in real-world applications like data cleaning, web scraping, and automation.
References
- Internal Reference: https://savanka.com/category/learn/python/
- External Reference: https://www.w3schools.com/python/