Regex Python not working correctly
<p>Hy, I have an issue with regex python 3.</p>

<p><strong>Here is my code :</strong></p>

<pre><code># 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")
</code></pre>

<p><strong>My issue :</strong></p>

<p>I have two print message success when i start my programm :</p>

<pre><code>I find tk_common in out-file
I find tk_text in out-file
</code></pre>

<p>But in fact, <strong>it should not :</strong></p>

<pre><code>$ cat tmp/out-file.txt | grep "tk_common\|tk_text"
&lt;div class="tk_common"&gt;
</code></pre>

<p>Any idea ?
Thanks,</p>

<pre><code>if regex1.search is not None:
</code></pre>

<p>Should be <code>result</code></p>

<pre><code>if result is not None
</code></pre>

<p>Because <code>re.compile().search</code> is a function, and most definitely not <code>None</code>. You want to look at the return value.</p>

<p>Also, your loop</p>

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

<p>If you find it on line 1, but then not on line 2, your result is going to be None and give a false negative. You should do <code>if result: break</code></p>

<p>Using the Regex engine is a little overkill to simple do "is this string a substring". You can just do something like this</p>

<pre><code>found_tk = False
with open('filename', 'r') as file_handle:
    for line in file_handle:
        if 'tk_text' in line:
            found_tk = True
            break
</code></pre>

python python-3.x