Is it worth using Python's re.compile?

前端 未结 26 2246
旧时难觅i
旧时难觅i 2020-11-22 12:51

Is there any benefit in using compile for regular expressions in Python?

h = re.compile(\'hello\')
h.match(\'hello world\')

vs



        
26条回答
  •  面向向阳花
    2020-11-22 13:24

    Besides the performance.

    Using compile helps me to distinguish the concepts of
    1. module(re),
    2. regex object
    3. match object
    When I started learning regex

    #regex object
    regex_object = re.compile(r'[a-zA-Z]+')
    #match object
    match_object = regex_object.search('1.Hello')
    #matching content
    match_object.group()
    output:
    Out[60]: 'Hello'
    V.S.
    re.search(r'[a-zA-Z]+','1.Hello').group()
    Out[61]: 'Hello'
    

    As a complement, I made an exhaustive cheatsheet of module re for your reference.

    regex = {
    'brackets':{'single_character': ['[]', '.', {'negate':'^'}],
                'capturing_group' : ['()','(?:)', '(?!)' '|', '\\', 'backreferences and named group'],
                'repetition'      : ['{}', '*?', '+?', '??', 'greedy v.s. lazy ?']},
    'lookaround' :{'lookahead'  : ['(?=...)', '(?!...)'],
                'lookbehind' : ['(?<=...)','(?...)', '(?P=name)', '(?:)'],},
    'escapes':{'anchor'          : ['^', '\b', '$'],
              'non_printable'   : ['\n', '\t', '\r', '\f', '\v'],
              'shorthand'       : ['\d', '\w', '\s']},
    'methods': {['search', 'match', 'findall', 'finditer'],
                  ['split', 'sub']},
    'match_object': ['group','groups', 'groupdict','start', 'end', 'span',]
    }
    

提交回复
热议问题