Is it worth using Python's re.compile?

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

    Interestingly, compiling does prove more efficient for me (Python 2.5.2 on Win XP):

    import re
    import time
    
    rgx = re.compile('(\w+)\s+[0-9_]?\s+\w*')
    str = "average    2 never"
    a = 0
    
    t = time.time()
    
    for i in xrange(1000000):
        if re.match('(\w+)\s+[0-9_]?\s+\w*', str):
        #~ if rgx.match(str):
            a += 1
    
    print time.time() - t
    

    Running the above code once as is, and once with the two if lines commented the other way around, the compiled regex is twice as fast

提交回复
热议问题