11.6. Regexp Compile

11.6.1. About

  • re.compile()

  • Used when pattern is reused (especially in the loop)

11.6.2. Examples

Listing 11.8. 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,}$'
DATA = [
    'mark.watney@nasa.gov',
    'Mark.Watney@nasa.gov',
    '+mark.watney@nasa.gov',
    'mark.watney+@nasa.gov',
    'mark.watney+newsletter@nasa.gov',
    'mark.watney@.gov',
    '@nasa.gov',
    'mark.watney@nasa.g']

for email in DATA:
    re.match(PATTERN, email)
Listing 11.9. 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,}$')
DATA = [
    'mark.watney@nasa.gov',
    'Mark.Watney@nasa.gov',
    '+mark.watney@nasa.gov',
    'mark.watney+@nasa.gov',
    'mark.watney+newsletter@nasa.gov',
    'mark.watney@.gov',
    '@nasa.gov',
    'mark.watney@nasa.g']

for email in DATA:
    PATTERN.match(email)