![]() |
VOOZH | about |
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:
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.
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.
Output
Valid EmailIn 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.
Output
Valid Phone Number