Is it worth using Python's re.compile?

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

    According to the Python documentation:

    The sequence

    prog = re.compile(pattern)
    result = prog.match(string)
    

    is equivalent to

    result = re.match(pattern, string)
    

    but using re.compile() and saving the resulting regular expression object for reuse is more efficient when the expression will be used several times in a single program.

    So my conclusion is, if you are going to match the same pattern for many different texts, you better precompile it.

提交回复
热议问题