My Three Months Journey Through The She Code Africa Mentorship Program(Cohort 3)

My Three Months Journey Through The She Code Africa Mentorship Program(Cohort 3)

A little background story...

I started out my tech journey this year, basically at the start of the lockdown with learning Python. I had wanted to start earlier but industrial training and school work took up most of my time. Well, during the start of lockdown, I finally started learning, shuffling between learning with Udemy and a textbook by Tony Gaddis (Starting Out With Python) but I was not learning as fast as I wanted to.

To cut the long story short, a friend of mine, (thank you Chizzy) informed me about the Cohort 3 of the She Code Africa mentorship program which then was taking applications and I registered. Luckily I scaled the selection process and it has been an amazing journey ever since.

My Journey Through The Program

It has been three months of intense learning in the beginner python track with my mentor Jeremiah Olufayo and other mentees, and it's been the most rewarding time ever. I have gone from being a complete novice to an intermediate level and I'll just share a little of what I learned through the program, particularly regular expressions.

We covered the basics from variables to strings to functions up to regular expressions, sqlite3, code reviews and testing.

All You Need to Know About Regular Expressions(RegEx)

Think of searching for a word or group of words in a document or webpage, the most common shortcut is Ctrl+F right? Regular expressions goes a step further, it instead allows you to specify a particular pattern of text that you want to search for.

This brings about the question "What is A Regular Expression?"

What is A Regular Expression?

A Regular Expression in a simple definition is a description for a pattern of text.

A Regular Expression otherwise called RegEx is a sequence of characters that form a search pattern. It can be used to check if a string contains the specified search pattern.

"Knowing [regular expressions] can mean the difference between solving a problem in 3 steps and solving it in 3,000 steps. When you’re a nerd, you forget that the problems you solve with a couple keystrokes can take other people days of tedious, error-prone work to slog through." -Cory Doctorow

Steps in Using Regular Expressions.

Step 1: To use RegEx in python, you need to import the re module.

import re

Step 2: Create a RegEx object with the re.compile function. Use a raw string r' in order to avoid repeating backslashes. (Typing r'd\d\d-\d\d\d\d' is easier than typing out '\\d\\d\\d-\\d\\d\\d\\d').

Step 3: Pass the string you want to search into the Regex object’s search() method. This returns a Match object.

Step 4: Call the Match object’s group() method to return a string of the actual matched text.

Metacharacters in RegEx

Metacharacters are characters with special meaning. They include:

  • [] : This describes a set of characters.

  • \ : This signals a special sequence. It is also known as an escape character which is used to escape certain special characters.

  • . : This matches any character except a newline character(\n).

  • ^ : This matches the beginning of a string. For example: "^Hi"
  • $ : This matches the end of a string. For example: "there$"
  • * : This matches zero or more occurrences. For example: "air*"
  • + : Signals one or more occurrences.
  • {} : This matches exactly the specified number of occurrences.
  • | : This matches either one or another. It is called a pipe.
import re

persons = "Mandy Jacobs and Trey Smith"
regex = re.compile(r'Mandy Jacobs|Trey Smith')
mo1 = regex.search(persons)
print(mo1.group())

The Output:

Output:
Mandy Jacobs

Notice that it matched the first name only. This is because both names appear in the same string, therefore it matches the first occurrence of matching text. Same way if you have:

import re

persons = "Mandy Jacobs and Trey Smith"
regex = re.compile(r'Trey Smith|Mandy Jacobs')
mo2 = regex.search(persons)
print(mo2.group())

The Output will be

Output:
Trey Smith

If you want to match one of several patterns as part of your RegEx, say, Corndogs, Cornsyrup, Cornflakes, Cornflower; since all the strings start with Corn, you could specify that prefix only once. The RegEx pattern would be written as:

cornRegex = re.compile(r'Corn|dogs|syrup|flakes|flower')

Example:

import re

cornRegex = re.compile(r'corn(dogs|syrup|flakes|flower)')
statement = "There are enough corndogs to go round."
mo = cornRegex.search(statement)
print(mo.group())
print(mo.group(1))

The Output:

corndogs
dogs

The Regex pattern matches corn and dogs. In the first group, it matches corndogs while in the second group, it matches only dogs.

  • () : This signals a group which returns the actual matched text.
# Example:
import re

string = "My phone number is 234-703-893-7824"
phoneNum_RegEx = re.compile(r'(\d\d\d)-\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNum_RegEx.search(string)
print('Phone Number found: ' + mo.group())
print("Area Code is: " + mo.group(1))

The Output of the code will be:

Phone number found: 234-703-893-7824
Area Code is: 234

In the first grouping which is mo.group() it returns the entire matched text which in this case is the phone number 234-703-893-7824 while in the second grouping which is mo.group(1), it returns only the first matched pattern which is in parentheses, that is, (\d\d\d). mo is a variable that represents matched object.

Special Sequences in RegEx

A Special sequence is a backslash() followed by any of the following characters listed below and has a special meaning. [w3schools.com/python/python_regex.asp]

  • \A : Returns a match if the specified characters are at the beginning of the string. Example: "\AThe"

  • \b : Returns a match where the specified characters are at the beginning or at the end of a word; (the "r" in the beginning is making sure that the string is being treated as a "raw string"). Example: r"\bain", r"ain\b"

  • \B : Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word; (the "r" in the beginning is making sure that the string is being treated as a "raw string"). Example: r"\Bain", r"ain\B"

  • \d : Returns a match where the string contains digits (numbers from 0-9). Example: "\d"

  • \D : Returns a match where the string DOES NOT contain digits. Example: "\D"

  • \s : Returns a match where the string contains a white space character. Example: "\s"

  • \S : Returns a match where the string DOES NOT contain a white space character.

  • \w : Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character).

  • \W : Returns a match where the string DOES NOT contain any word characters.

  • \Z : Returns a match if the specified characters are at the end of the string.

Functions in RegEx

These functions enable us to search a string for a match.

  • findall: Returns a list containing all matches, as long as there are no groups in the regular expression. If there are groups in the regular expression, it returns a list of tuples.

  • search: Returns a Match object if there is a match anywhere in the string.

  • split: Returns a list where the string has been split at each match.

  • sub: Replaces one or many matches with a string.

Examples:

1) Using the findall() function

import re

phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')  # has no groups
mo = phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')
print(mo)

Output:
['415-555-9999', '212-555-0000']
import re

phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)') # has groups
mo = phoneNumRegex.findall('Cell: 415-555-9999 Work: 212-555-0000')
print(mo)

Output:
[('415', '555', '9999'), ('212', '555', '0000')]

2) Using the split() function

import re

phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')  # has groups
mo = phoneNumRegex.split('Cell: 415-555-9999 Work: 212-555-0000')
print(mo)

Output:
['Cell: ', '415', '555', '9999', ' Work: ', '212', '555', '0000', '']

3) Using the sub() function

import re

txt = "The rain in Spain"
x = re.sub("\s", "9", txt)  #This replaces every whitespace character with "9".
print(x)

Output:
The9rain9in9Spain

Character Sets

A set is a set of characters inside a pair of square brackets [] with a special meaning:

  • [arn]: Returns a match where one of the specified characters (a, r, or n) are present.

  • [a-n]: Returns a match for any lower case character, alphabetically between a and n.

  • [^arn]: Returns a match for any character EXCEPT a, r, and n.

  • [0123]: Returns a match where any of the specified digits (0, 1, 2, or 3) are present.

  • [0-9]: Returns a match for any digit between 0 and 9.

  • [0-5][0-9]: Returns a match for any two-digit numbers from 00 and 59.

  • [a-zA-Z]: Returns a match for any character alphabetically between a and z, lower case OR upper case.

  • [+]: In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the string.

Example:

#This regular expression pattern matches emails
import re

emails = """
IhuomaOgbuji@futo.edu
angelsimon87@gmail.com
alexx-31-lazzo@cisco.net
"""

pattern = re.compile(r'[a-zA-Z0-9.-]+@[a-zA-Z-]+\.(edu|com|net)')

matches = pattern.finditer(emails)

for match in matches:
    print(match)

Output:

<re.Match object; span=(1, 22), match='IhuomaOgbuji@futo.edu'>
<re.Match object; span=(23, 45), match='angelsimon87@gmail.com'>
<re.Match object; span=(46, 70), match='alexx-31-lazzo@cisco.net'>

The finditer function iterates through the emails to return all the matches in emails.

References

  1. [w3schools.com/python/python_regex.asp]

  2. AL SWEIGART. Automate The Boring Stuff With Python Practical Programming For Total Beginners.

Thank you to all who have made this journey worthwhile. My mentor Jerry, my POC Lola, my fellow mentees, Nimah, Hafsah, Dr. Rabi, Faith, Neema and others. Thank you!