2016-09-24 7 views
0

Hyは働いていない、私はここで正規表現の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") 

私の問題:

私は2枚のプリントを持っています私のプログラムを起動するとメッセージの成功:

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"> 

任意のアイデア? re.compile().searchが最も確実None関数ではなく、かつので おかげで、

+0

regex1.searchとregex2.searchは( 'NONE'ではありません)関数です。あなたは結果である 'result'を探しています。あなたのコードに加えて、最後の行だけをチェックします。なぜなら、エリートラインに行き、各行をチェックした後に結果を調べるからです。 – syntonym

答えて

0
if regex1.search is not None: 

result

if result is not None 

であるべき。あなたは戻り値を見たいと思う。また

、あなたのループ

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

あなたは2行目に1行目にそれを見つけるが、その後でない場合は、あなたの結果はNoneと偽陰性を与えるために起こっています。あなたはする必要がありますif result: break

Regexエンジンを使用することは少し難しいです "この文字列は部分文字列です"。あなたはちょうどこの

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

このラインのような何かを行うことができます:regex1.searchはないそのメソッドの戻り値に、search方法を参照するため

if regex1.search is not None: 

Noneになることはありません。したがって、あなたのコードは常に一致すると考えています。

regex1.searchではなく、resultという変数をチェックしたと思います。

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") 

それはとにかく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")