Regular expressions are very useful to the Python coder, especially if they have to deal with a lot of output in the form of text. Through this tutorial, you will learn how to find an email address from a Python long string object by making use of the regular expressions.
Before going any further, make sure to launch a new Python interactive console in your own operating system with the main purpose of practicing the knowledge being shared in here, by yourself.
Once you have managed to open a new Python interactive shell in your own operating system, use the following syntax to define a string object.
email_string = 'here is stored an email [email protected]'
Now that you have defined the above string object in your own Python interactive shell, we need to define a custom pattern, so we can build the regular expression.
Based on my experience with regular expressions in the Python computer programming language, I have come to the conclusion that their true power stands in their ability to define custom patterns, not just fixed characters.
Special characters are being used to define custom patterns which can later be used as part of regular expressions in the Python computer programming language. Based on my personal experience with the regular expressions in the Python computer programming language, there are many special characters one can make use of to write their custom patterns.
For the purpose of the this tutorial, the special character which we truly need to construct our pattern for our custom regular expression, is the one being shown below.
According to the official documentation about the Python computer programming language, when the above special character is being used in a custom regular expression, it matches a letter or a digit or an underbar [a-zA-Z0-9_].
We are going to use the above special character to construct the custom pattern for our regular expression. Another special character which we need to include in our custom pattern, is the one shown below.
According the official documentation about the Python computer programming language, the above special character matches one or more occurrences of the pattern to it’s left.
So if we manage to group our special character in square brackets like shown in the following piece of Python code, we can easily match more than one character.
custom_pattern = r'[\w.][email protected][\w.]+'
According to my personal experience with the regular expressions in the Python computer programming language, the . declared above in the custom pattern, means a literal dot.
Now, make use of the following piece of Python code to parse the email address from the string object which we defined in the beginning of this short tutorial on regular expressions.
match_obj = re.search(custom_pattern, email_string) if match_obj: print(match_obj.group())
Once the above piece of Python code got executed on my Python interactive console, I got the following output.