在多次调用的函数内编译正则表达式

Lor*_*ein 14 python regex

如果你在一个函数内编译一个正则表达式,并且该函数被多次调用,那么Python每次都会重新编译正则表达式,还是Python缓存编译的正则表达式(假设正则表达式没有改变)?

例如:

def contains_text_of_interest(line):
    r = re.compile(r"foo\dbar\d")  
    return r.match(line)

def parse_file(fname):
    for line in open(fname):
        if contains_text_of_interest(line):
           # Do something interesting
Run Code Online (Sandbox Code Playgroud)

Ned*_*der 12

实际上,如果你查看re模块中的代码,re.compile函数就像所有其他函数一样使用缓存,因此反复编译相同的regex是非常便宜的(字典查找).换句话说,将代码编写为最易理解或可维护或表达,并且不必担心编译正则表达式的开销.


Din*_*ngo 6

如果你想避免每次调用re.compile()的开销,你可以这样做:

def contains_text_of_interest(line, r = re.compile(r"foo\dbar\d")): 
    return r.match(line) 
Run Code Online (Sandbox Code Playgroud)

  • +1我的话,我从未想过我会看到Python的默认参数处理*有用*. (4认同)