2014-02-12 199 views
-1

在python're'模块中,我想使用大量的re.findall()和re.sub()的一百万次调用。我想在一个字符串中查找所有出现的模式,然后用一个固定的字符串替换它们。防爆。字符串中的所有日期都以列表的形式返回,并在原始列表中将其替换为'DATE'。我怎样才能将两者结合为一体?加速python正则表达式匹配

回答

1

​​3210的替换的参数可以是一个可调用:

dates = [] 
def store_dates(match): 
    dates.append(match.group()) 
    return 'DATE' 

data = re.sub('some-date-string', store_dates, data) 

# data is now your data with all the date strings replaced with 'DATE' 
# dates now has all of the date strings that matched your regex