Is it worth using Python's re.compile?

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

    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.

提交回复
热议问题