Regular Expressions pt 2

Last time I went over Regular Expressions, I covered match and search. While similar they had separate applications that can be useful in user authentication in Python apps. Today I’ll add to that with the last 2 of the 4 main regular expressions. Find All and Find & Replace.

findall does what it says. It finds ever iteration of the string we assign to our pattern. Like before we first need to make sure we import our regular expression module to our code and assign a pattern we wish to look for.

From there we need to write an if/else statement. However we can also just ask our code to print what it finds. If we go with the if/else statement, we should get “Sheep found!” when we run the code.

If we go with just the print method, it will look like this and print each iteration of our pattern that we requested it find.

Either way is good but in my opinion, to make sure it’s doing as you ask, starting with the print method is a good way to start before writing and if/else statement for your code.

Next up, we use find & replace. This is useful if we want to change something in a string we have. Unlike the other 3 Regular Expressions, this time we start off defining our string then our pattern. We do this so that one our sting is created, we can pass our pattern into our regular expression re.sub that will replace what we need it to. In this instance we’ll code it so that the name is replaced.

Once we have everything established, we need to ask Python to print our new string. For this I’ll have it print both the original string with our newstring under it.

When we run our code, we see that the string does in fact change and Mochi the Sheep is now Peep the Sheep.

Hopefully seeing it in action helps you understand how Regular Expressions can work for us in code.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pilahi Moran

Pilahi Moran

Full Stack Software Engineer, Artist, Cook, and Illustrator. Mother of 2 cockatiels and 2 cats.