6 Tips about Python Regular Expressions

Gustavo Santos
7 min readDec 4, 2022
Photo by Raphael Schaller on Unsplash

If you got to this post it is probably because of the controversial fame of Regular Expressions, or just RegEx for short…

But what are those?

Well, regex is an encoded expression — or a sequence of characters — used to match any kind of patterns in a string. In other words, it is like a master key that can open many doors.

Using operators like in or the function .find( ) are useful for sure, but when you are looking for a single pattern like ‘ABC’.

s = "Now I know my ABC"
'ABC' in s
out: True
s.find('ABC')
out: 14

Now, if we are looking for ‘ABC’ or ‘abc’ or ‘cde’ or whatever other sequence, That is when the regex become really helpful, and I want to show you 6 tips for nailing RegEx now. So, import re in your Python and come with me.

1. Using the re.search( )

This method is very similar to the .find( ) above, except for the output and the possibilities you have with it. find will give you only exact match and the position of the initial letter while search can give you much more information, such as start, end, and the string matched. Let’s test it:

s = "Now I know my ABC"
re.search('I',s)
out: <_sre.SRE_Match object; span=(4, 5), match='I'>

--

--

Gustavo Santos

Data Scientist. I extract insights from data to help people and companies to make better and data driven decisions. | In: https://www.linkedin.com/in/gurezende/