2013-05-07 77 views
1

我想在多个文件中“grep”多个正则表达式。我把所有的正则表达式中的一个文件(每行一个),我在下面的方式加载,构建一个“超级正则表达式”:Python:如何在多个文件中搜索多个模式

dic = open('regex.dic') 
rex = [] 
for l in iter(dic): 
    if not l.startswith('#'): 
     rex.append('^.*%s.*$' % l.strip()) 
rex = '|'.join(rex) 
debug('rex='+rex) 
global regex 
regex = re.compile(rex, re.IGNORECASE|re.MULTILINE) 
dic.close() 

然后我检查我的文件是这样的:

with open(fn, 'r') as f: data = f.readlines() 
for i, line in enumerate(data): 
    if len(line) <= 512: #Sanity check 
     if regex.search(line): 
      if not alreadyFound: 
       log("[!]Found in %s:" % fn) 
       alreadyFound = True 
       found = True 
       copyFile(fn) 
      log("\t%s" % '\t'.join(data[i-args.context:i+args.context+1]).strip()) 

这可行。我觉得这真的没有效率和危险(dic中的一些正则表达式可能会打破“超正则表达式”)。我在考虑循环在正则表达式阵列,但这将意味着多次扫描每个文件:/

关于如何做到这一点的任何明智的想法?谢谢!

+0

我其实并没有真正看到这个问题。不一定非常优雅,但正如你所说,它可以相对有效地完成工作。 – jdotjdot 2013-05-07 15:10:29

回答

1
if l and l[0] != '#': 
    try: 
     re.compile(s) 
    except: 
     #handle any way you want 
    else: 
     rex.append('^.*({0}).*$'.format(l.strip())) 

这将照顾畸形的正则表达式。