Python tutorial on using regular expressions
In this first Python tutorial on regular expression, we will extract out the telephone pattern from a this string …
The telephone is (123) 456-7890
The regular expression that matches that telephone format is …
\(\d{3}\) \d{3}-\d{4}
Because there are so many backslashes here, we put this regular expression into Python’s raw string and pass it to the regular expression compile method which will give us an regular expression pattern…
The regular expression pattern has a search method where we pass it the string to search. The result is a Match object, which still does not give us the telephone. We call the group() method on it to get the value of the telephone found that match the pattern.
The match object will by None if no match is found. Note that we had to import the “re” module.
The above example only finds the first instance that matches the pattern. If there was a second telephone it would not find it. If you want to find all matches, you use the “findall” method …
In this case the result that you get back is a list. So you can iterate through it.
Compiling the regular expression into a pattern is useful if you are going to use the pattern multiple times. But if it is an one-time use, you can do just call the “search” class method on the “re” class like this…
The search class method takes pattern as the first parameter and the string to search as the second parameter.