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>

<p>This line:</p>

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

<p>will never be <code>None</code> because <code>regex1.search</code> refers to the <code>search</code> method, not to the return value of that method. Therefore your code always thinks that there is a match.</p>

<p>I think that you meant to check the <code>result</code> variable, not <code>regex1.search</code>.</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)
        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")
</code></pre>

<p>It is unnecessary to compile the re pattern because it will be <a href="https://docs.python.org/3/library/re.html#re.compile" rel="nofollow">cached by the re module</a> anyway. Also, since you don't use the match object saved in <code>result</code>, you could just test the result of <code>re.search()</code> directly:</p>

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

python python-3.x