Python Regular Expression Exercises
Let’s check out some exercises that will help you understand Regular Expressions better.
From the list keep only the lines that start with a number or a letter after > sign.
Write a regex so that the full email addresses are extracted.
One way to approach this problem is:
1- include everything that’s non-space before the “@” sign
2- adding the “@” sign
3- everything non-space after the “@” sign.
This example really shows the versatility of regex because with this format, you will catch the emails regardless of different suffixes (.co.uk, .gov.fr, .co.jp etc.)
Regular Expression for everything except space is:
\S : Non-space characters
\S you can apply non-space to one or more characters
regex = r'\S+@\S+'
Note: So the part inside quotes is purely regex. But you might be wondering what r is doing in front. r’text here’ is a fantastic trick in Python that can help you avoid numerous conflicts such as back slash misinterpretations while typing directories etc.
Raw string can help you remember and understand the function of r.
It’s a good practice to have sometimes, otherwise if you type your string without the r backslashes will be trated as escape characters.
Regex Cheat Sheet