2016-09-24 28 views
0

海兰,我有一个问题用正则表达式的Python 3正则表达式的Python工作不正常

这里是我的代码:

# Here is regex 1, have to find tk_common on file tmp/out-file.txt 
regex1 = re.compile(r'tk_common') 
with open("tmp/out-file.txt") as f: 
     for line in f: 
        result = regex1.search(line) 

# If found : 
if regex1.search is not None: 
    print("I find tk_common in out-file") 

# else : 
else: 
    print("I didn't find tk_common in out-file") 


# And here is the second one 
regex2 = re.compile(r'tk_text') 
with open("tmp/out-file.txt") as f: 
     for line in f: 
        result = regex2.search(line) 

if regex2.search is not None: 
    print("I find tk_text in out-file") 
else: 
    print("I didn't fint tk_text in out-file") 

我的问题:

我有两个打印消息成功,当我开始我的程序:

I find tk_common in out-file 
I find tk_text in out-file 

但事实上,它不应该:

$ cat tmp/out-file.txt | grep "tk_common\|tk_text" 
<div class="tk_common"> 

任何想法? 谢谢,

+0

regex1.search和regex2.search的功能(不是'None')。你正在寻找结果的结果。除了你的代码将只检查最后一行,因为去everyline和你检查每一行后,你调查结果。 – syntonym

回答

0
if regex1.search is not None: 

应该result

if result is not None 

因为re.compile().search是一个函数,而绝对不是None。你想看看返回值。

此外,你的循环

regex1 = re.compile(r'tk_common') 
with open("tmp/out-file.txt") as f: 
    for line in f: 
       result = regex1.search(line) 

如果您发现第1行,但后来不就行2,你的结果将是无,给假阴性。你应该这样做if result: break

使用正则表达式引擎对于简单的做法是“一个字符串是一个子字符串”有点矫枉过正。你可以做这样的事情

found_tk = False 
with open('filename', 'r') as file_handle: 
    for line in file_handle: 
     if 'tk_text' in line: 
      found_tk = True 
      break 
1

这条线:

if regex1.search is not None: 

永远不会None因为regex1.searchsearch方法,而不是该方法的返回值。因此,你的代码总是认为有匹配。

我认为你的意思是检查result变量,而不是regex1.search

regex1 = re.compile(r'tk_common') 
with open("tmp/out-file.txt") as f: 
    for line in f: 
     result = regex1.search(line) 
     if result is not None: 
      print("I find tk_common in out-file") 
      break 
    else: 
     print("I didn't find tk_common in out-file") 

无论如何编译re模式是不必要的,因为它将是cached by the re module。此外,由于不使用保存在result匹配的对象,你可以只直接测试的re.search()结果:

with open("tmp/out-file.txt") as f: 
    for line in f: 
     if re.search(r'tk_common', line) is not None: 
      print("I find tk_common in out-file") 
      break 
    else: 
     print("I didn't find tk_common in out-file") 
相关问题