Python
9 Practical Examples of Using Regular Expressions in Python
Handling text like a guru
Published in
5 min readApr 13, 2023
Whenever you meet problems with text manipulations, regular expressions (regex) are always your best friends.
However, it’s hard and impossible to remember all the complex rules of them. Even merely reading the syntax is overwhelming.
Therefore, the best way to learn regex is by learning practical examples of them.
This article will summarize 9 commonly-used regex tricks in daily programming scenarios. After reading, the regex will be just a cup of tea for you. 🍵
1. Validating Email Addresses
Checking the validity of an email address is a classic use case of regex.
Here’s an example program:
import re
def val_email(email):
pattern = r"^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z]{2,}$"
if re.match(pattern, email):
print("Valid email address:)")
else:
print("Invalid email address!!")
val_email(email="elon@example.com")
# Valid email address:)
val_email(email="elonexample.com")
# Invalid email address!!
val_email(email="elon@example.c")
# Invalid email address!!