import re
def find_string(file_name, word):
with open(file_name, 'r') as a:
for line in a:
line = line.rstrip()
if re.search("^{}$".format(word),line):
return True
return False
if find_string('/tmp/myfile', 'hello'):
print("found")
else:
print("not found")
myfile:
hello world #does not match
hello #match
如果删除^和$,则将匹配,但也将匹配“ he”,“ hel”等。如果一行上有多个单词,如何匹配确切的字符串?