海兰,我有一个问题用正则表达式的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">
任何想法? 谢谢,
regex1.search和regex2.search的功能(不是'None')。你正在寻找结果的结果。除了你的代码将只检查最后一行,因为去everyline和你检查每一行后,你调查结果。 – syntonym