Is it worth using Python's re.compile?

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

提交回复
热议问题