Regex is a built-in library in Python. You can use the re module to work with regular expressions. Here are some basic examples of how to use the re module in Python:
Examples of Regular Expression in Python
We can import it in our Python by writing the following import statement in the Python script.
import re
//or
import re as regex
Now let us see a few examples to understand how Regex works in Python.
Email Validator
In this example, we will create an email validator in Python with the help of regex module. We defined the pattern in the compile() function of the re module. The pattern matching include \w+ which matches for 1 or more character, i.e., a-z, A-Z, 0-9, _. The @ match for the @ special symbol and the \. matches for the '.' dot charater.
#importing the regex module
import re
#defining the function
def emailValidator(s):
#creating the patter
pattern = re.compile(r'\w+@\w+\.\w+')
#matching the patter
if pattern.match(s) :
return True
return False
#input email pattern : exammple@email.com'
s = "geeksforgeeks@gmail.com"
if emailValidator(s):
print("Valid Email")
else:
print("Invalid Email")
Output
Valid EmailPhone Number Validator
In this example, we will create a phone number validator. It should be in this pattern : 111-111-1111. The pattern that is provided to the compile() function is \d{3} which matches for exact 3 digits and the - which will math the literal hyphen. Then again we use \d{4} to match exact 4 digit.
#importing the regex module
import re as regex
#defining the function
def phoneValidator(s):
#creating the patter
pattern = regex.compile(r'\d{3}-\d{3}-\d{4}$')
#matching the patter
if pattern.match(s) :
return True
return False
#phone number should be in this pattern : 111-111-1111
s = "987-654-3210"
if phoneValidator(s):
print("Valid Phone Number")
else:
print("Invalid Phone Number")
Output
Valid Phone Number