Python:查找文件中是否存在给定的正则表达式

时间:2014-08-23 16:43:28

标签: python regex

我想如果一个模式存在于一个非常大的文件中。蛮力技术将是:

match = re.findall("xyz", text)
    if(len(match) > 0):
        print 'Match found'

findall找到所有匹配项。有没有办法在找到第一个实例后终止?

2 个答案:

答案 0 :(得分:2)

如果hwnd的解决方案不起作用,请尝试re.finditer()。它返回一个迭代器。如果您使用next()来检查第一场比赛,则不会再扫描任何比赛 - 您只能看到第一场比赛。

import re

m = re.finditer( 'beer', open('zfind.py').read() ).next()
print m and m.group(0)

输出

beer

答案 1 :(得分:1)

你可以发挥作用。

def isitthere(file_to_check, pattern):
    with open(file_to_check, 'r') as file:
        for line in file:
            if pattern in line:
                return True    #return on first match stops the iteration
            else:
                continue
    return False

if isitthere(file_to_check, pattern):
    print 'Match Found!'

或使用re.search:

def isitthere(file_to_check, pattern):
    with open(file_to_check, 'r') as file:
        for line in file:
            if re.search(pattern, line) != None:
                return True          #return on first match stops the iteration
            else:
                continue
    return False

if isitthere(file_to_check, pattern):
    print 'Match Found!'