Regex in Python
Regular expressions, also called regex, are descriptions of a pattern of text. It can detect the presence or absence of a text by matching it with a particular pattern and also can split a pattern into one or more sub-patterns. For example, a \d in a regex stands for a digit character — that is, any single numeral between 0 and 9.
Check Phone Numbers Using Regex In Python
Following regex is used in Python to match a string of three numbers, a hyphen, three more numbers, another hyphen, and four numbers.
Any other string would not match the pattern.
\d\d\d-\d\d\d-\d\d\d\d
Regular expressions can be much more sophisticated. For example, adding a 3 in curly brackets ({3}) after a pattern is like saying, “Match this pattern three times.” So the slightly shorter regex is as follows:
\d{3}-\d{3}-\d{4}
It matches the correct phone number format.
Pattern Matching with Regular Expressions
A Regex object’s search() method searches the string it is passed for any matches to the regex. Match objects have a group() method that will return the actual matched text from the searched string. You can also see Regex cheetsheet for more information.
Example: Import the regex module with import re. Create a Regex object with the re.compile() function. (Remember to use a raw string.) Pass the string you want to search into the Regex object’s search() method. This returns a Match object. Call the Match object’s group() method to return a string of the actual matched text.
Python3
# Python program to illustrate # Matching regex objects import re # regex object phoneNumRegex = re. compile (r '\d\d\d-\d\d\d-\d\d\d\d' ) mo = phoneNumRegex.search( 'My number is 415-555-4242.' ) print ( 'Phone number found: ' + mo.group()) |
Output:
Phone number found: 415-555-4242
Pattern matching in Python with Regex
You may be familiar with searching for text by pressing ctrl-F and typing in the words you’re looking for. Regular expressions go one step further: They allow you to specify a pattern of text to search for. In this article, we will see how pattern matching in Python works with Regex.