Is it worth using Python's re.compile?

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

    Legibility/cognitive load preference

    To me, the main gain is that I only need to remember, and read, one form of the complicated regex API syntax - the .method(xxx) form rather than that and the re.func(, xxx) form.

    The re.compile() is a bit of extra boilerplate, true.

    But where regex are concerned, that extra compile step is unlikely to be a big cause of cognitive load. And in fact, on complicated patterns, you might even gain clarity from separating the declaration from whatever regex method you then invoke on it.

    I tend to first tune complicated patterns in a website like Regex101, or even in a separate minimal test script, then bring them into my code, so separating the declaration from its use fits my workflow as well.

提交回复
热议问题