11.6. Regexp Compile

11.6.1. About

  • re.compile()

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

11.6.2. Example

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

for email in INPUT:
    re.match(PATTERN, email)
Listing 414. 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)