3. Regex pattern compilation

  • re.compile()

3.1. Without compilation

Listing 311. Compiles at every loop iteration, and then matches
import re


PATTERN = r'^[a-zA-Z0-9][\w.+-]*@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]{2,}$'
INPUT = [
    'ma[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '@nasa.gov',
    '[email protected]']

for email in INPUT:
    re.match(PATTERN, email)

3.2. With compilation

Listing 312. Compiling before loop, hence matching only inside
import re


PATTERN = re.compile(r'^[a-zA-Z0-9][\w.+-]*@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]{2,}$')
INPUT = [
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '@nasa.gov',
    '[email protected]']

for email in INPUT:
    PATTERN.match(email)