Is it worth using Python's re.compile?

前端 未结 26 1825
旧时难觅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:30

    In general, I find it is easier to use flags (at least easier to remember how), like re.I when compiling patterns than to use flags inline.

    >>> foo_pat = re.compile('foo',re.I)
    >>> foo_pat.findall('some string FoO bar')
    ['FoO']
    

    vs

    >>> re.findall('(?i)foo','some string FoO bar')
    ['FoO']
    
    0 讨论(0)
  • 2020-11-22 13:30

    There is one addition perk of using re.compile(), in the form of adding comments to my regex patterns using re.VERBOSE

    pattern = '''
    hello[ ]world    # Some info on my pattern logic. [ ] to recognize space
    '''
    
    re.search(pattern, 'hello world', re.VERBOSE)
    

    Although this does not affect the speed of running your code, I like to do it this way as it is part of my commenting habit. I throughly dislike spending time trying to remember the logic that went behind my code 2 months down the line when I want to make modifications.

    0 讨论(0)
提交回复
热议问题