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 = [
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '@nasa.gov',
    '[email protected]']

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 = [
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '@nasa.gov',
    '[email protected]']

for email in DATA:
    PATTERN.match(email)