更新时间:2023-11-26 08:57:52
正则表达式,\b
,指的是词边界处的空字符串,其中词是\w+
,或[A-Za-z0-9_]+
The regular expression, \b
, refers to the empty string at a word boundary, where word is \w+
, or [A-Za-z0-9_]+
如果您每行有一个名称(名称周围没有其他空格),您可以使用 ^{0}$
和 re.M
按行搜索或 re.MULTILINE
标志
If you have one name per line (with no other whitespace around the names), you can search by line with ^{0}$
with the re.M
or re.MULTILINE
flag
看起来像这样:
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...")
尽管评论和答案建议,如果你这样做
Although a comment and an answer suggest, if you do
if user in file.read()
你可能有误报.