Regular Expressions in Python with Examples
In this article, we are going to explore regular expressions in Python and show examples along the way. In short, a regular expression is just a pattern to find matches in a string. For example, if we wanted to see if a string had two a’s in a row, we can easily do that with a regular expression.
Lets just see what that regular expression pattern would look like.
/a{2}/
The / at the start and end of the regular expression just denotes the boundaries of the expression. The ‘a’ says we are looking for that character, and the curly braces with a 2 in them says we are looking where there are two a’s in a row.
Testing a Regular Expression Pattern
If you are wanting to test out your pattern to see if it matches https://regex101.com/. The pattern will be at the top and the string you want to test that pattern on will go below.
Regular Expression Module in Python
To query for a pattern using regular expressions, use the re module in python. There are some methods that will do what you need. Let’s run that pattern above in a python script.
import re
x = re.search('a{2}', 'baad')
if x:
print('Value found!')
else:
print('Value not found')
We use the search method and pass the pattern in first parameter, and the second is the string we are searching. x will be an object if there is a match in that string. You can also get the span of indexes where that pattern match was found.
import re
x = re.search('a{2}', 'baad')
print(x.span())
I plan on creating some more regular expression articles on this site, so stay tuned for those. Also, if you want more content, check out my YouTube Channel!
0 Comments