Is it worth using Python's re.compile?

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

    As an alternative answer, as I see that it hasn't been mentioned before, I'll go ahead and quote the Python 3 docs:

    Should you use these module-level functions, or should you get the pattern and call its methods yourself? If you’re accessing a regex within a loop, pre-compiling it will save a few function calls. Outside of loops, there’s not much difference thanks to the internal cache.

提交回复
热议问题