The re.compile function

Documentation

  1. Compiling Regular Expressions in the Regular Expression HOWTO.
  2. The re.compile function in module re.

Without compilation

import sys
import re   #regular expressions

filename = "/usr/share/dict/words"

try:
    lines = open(filename)
except FileNotFoundError:
    print(f"Sorry, could not find file \"{filename}\".")
    sys.exit(1)
except PermissionError:
    print(f"Sorry, no permission to open file \"{filename}\".")
    sys.exit(1)

for line in lines:
    line = line.rstrip("\n")   #Remove the trailing newline.
    if re.search(r"^(.).*\1$", line, flags = re.IGNORECASE):
        print(line)

lines.close()
sys.exit(0)
aa
aba
Ababua
abaca
Abama
etc.
yucky
yummy
Yurupary
zizz
Zmudz

With compilation

import sys
import re   #regular expressions

filename = "/usr/share/dict/words"

try:
    lines = open(filename)
except FileNotFoundError:
    print(f"Sorry, could not find file \"{filename}\".")
    sys.exit(1)
except PermissionError:
    print(f"Sorry, no permission to open file \"{filename}\".")
    sys.exit(1)

try:
    regularExpression = re.compile(r"^(.).*\1$", flags = re.IGNORECASE)
except re.error as error:
    print(error, file = sys.stderr)
    sys.exit(1)

print(f"type(regularExpression) = {type(regularExpression)}")

for line in lines:
    line = line.rstrip("\n")           #Remove the trailing newline.
    if regularExpression.search(line): #This search method accepts no flags.
        print(line)

lines.close()
sys.exit(0)
type(regularExpression) = <class 're.Pattern'>
aa
aba
Ababua
abaca
Abama
etc.
yucky
yummy
Yurupary
zizz
Zmudz

Things to try

  1. How much faster did the program get? Does the printing take up most of the time?
    import time
    
    #at the start of the program
    startTime = time.time()
    
    #at the end of the program
    endTime = time.time()
    print(f"elapsed time = {endTime - startTime}")