Python:如何在多个文件中搜索多个模式

时间:2013-05-07 15:07:18

标签: python regex

我想在多个文件上“grep”多个正则表达式。我有一个文件中的所有正则表达式(每行一个),我按以下方式加载,构建一个“超级正则表达式”:

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中的一些正则表达式可以打破“超级正则表达式”)。我正在考虑在正则表达式数组中循环,但这意味着多次扫描每个文件:/

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

1 个答案:

答案 0 :(得分:1)

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

这将处理格式错误的正则表达式。