Python

Well, this might be kind of cheating but I did find it to be a useful tool for an assignment I got in my Python class. I had to check that a string matches a certain set of criterias (e.g. has lowercase letters, uppercase letters and so on [and yes, it IS a password checker]).

In order to achieve this I have imported the re module and have precompiled the individual regular expressions so that my code is a bit more modular. I have also used string.punctuation to make a regular expression checking for special characters.

import re
import string

lowercase_regex = re.compile("[a-z]")
uppercase_regex = re.compile("[A-Z]")
special_regex = re.compile('[' + re.escape(string.punctuation) + ']')
numbers_regex = re.compile("[0-9]")

This is nice and all but how am I going to compare all of those regular expressions against a single string? I could do a for loop but that seems like unnecessary complication. I have decided to use the map() function along with a re.findall() lambda and match the string against all regexes one after the other.

By doing that, we get a list of lists (after converting the map object, of course) containing the matches to each one of the regular expressions, and we can easily know which regular expression did not match (by checking if the respective index in the list is an empty list) and act accordingly.

Let’s see it in action. First, I’ll put the relevant regular expressions I want to check the string against in a list so that map() can iterate through it, and the I’ll call I’ll do some magic and eventually check the list.

>>> password = "Hello"
>>> password_regex = [lowercase_regex, uppercase_regex, numbers_regex, special_regex]
>>> password_regex_matches_list = list(map(lambda regex: re.findall(regex, password), password_regex))
>>> password_regex_matches_list
[['e', 'l', 'l', 'o'], ['H'], [], []]

Here you can see that the string “Hello” returned 4 matches for the 1st regex, which checked for lowercase letters, then 1 match for the uppercase regex and no matches for the other 2 (numbers and special characters).

Bonus: If you’d like to know how many matches there are in total, you can do this easily by iterating through to list of list with itertools.chain simply import it and run through the list.

>>> from itertools import chain
>>> password_regex_matches = list(chain.from_iterable(password_regex_matches_list))
>>> password_regex_matches
['e', 'l', 'l', 'o', 'H']

And that’s it, you’ve unpacked the list and can access all matches!

If you liked this post, you can find all of my Python content right here

Categories:

About the Author

Orel Fichman

Tech Blogger, DevOps Engineer, and Microsoft Certified Trainer

No responses yet

Leave a Reply

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

Newsletter

Categories