所以我有:
def CheckUserExists(user):
with open("C:/~/database.txt", 'r') as file:
if re.search(user, file.read()):
return True
else:
return False
username = input("Please enter you Username: ")
if CheckUserExists(username) == True:
print("You exist!")
else:
print("This user does not exist...")
但是,如果您输入例如字母“a”并且是一个名为“brain”的用户;搜索选择 a 并返回 True。如何搜索整个单词?
我看过这里:How to check in Python if string is in a text file and print the line?但是我不明白这段代码:
re.search("\b{0}\b".format(w),line)
最佳答案
正则表达式,\b
,refers to the empty string at a word boundary ,其中单词是 \w+
,或 [A-Za-z0-9_]+
如果您每行有一个名称(名称周围没有其他空格),您可以使用 ^{0}$
和 re.M
按行搜索或 re.MULTILINE
标志
看起来像这样:
def CheckUserExists(user):
with open("C:/~/database.txt", 'r') as file:
if re.search('^{0}$'.format(re.escape(user)), file.read(), flags=re.M):
return True
else:
return False
username = input("Please enter you Username: ")
if CheckUserExists(username): # it's redundant to check if == True here
print("You exist!")
else:
print("This user does not exist...")
尽管有评论和答案建议,但如果您这样做
if user in file.read()
你可能有误报。
关于python - 检查文本文件中是否存在字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26391805/