Python在文件中搜索确切的字符串

问题描述 投票:0回答:1
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”等。如果一行上有多个单词,如何匹配确切的字符串?

python regex search
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.