Python Regular Expression to extract email from text

python-regular-expression-extract-email-feature-image

In this tutorial, we’re gonna look at way to use Python Regular Expression to extract email from a text.

Related Post: Python Regular Expression

Python Regular Expression to extract email

Import the regex module

All Python regex functions in re module. Remember to import it at the beginning of Python code or any time IDLE is restarted.

Create Regex object

We create a Regex object by passing a string value representing regular expression to re.compile().

To match the email pattern:

Get Match object

Regex object has search() method that searches the string that matches to the regex. It returns:
None if the regex pattern is not found
– a Match object if the pattern is found

Get matched text

We call Match object’s group() method to get the actual matched text from the searched string.

In this example, we use parentheses to group the pattern into several groups, so we can call groups() method that returns a tuple of multiple values.

Extract email

Now we want to store email data in some variables: email, domainName, toplevel. They are built from groups 0, 2, 3 (whole email, domain name, top level domain name).

Full code



By grokonez | January 6, 2019.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*