python - 检查文本文件中是否存在字符串

标签 python regex

所以我有:

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)

最佳答案

正则表达式,\brefers 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/

相关文章:

Python pymssql 错误 "TypeError: argument of type ' NoneType' is not iterable"when connecting to SQL server

python - 如何在日期间隔内添加缺失的日期?

python - Z3/Python 从模型中获取 python 值

c++ - 使用正则表达式进行输入验证

javascript - 在 JS 中拆分字符串

c# - 正则表达式仅替换给定 xml 节点中的子字符串

python - 从 json 文件创建 Python 事件资源对象

python - 将字符串打印到文本文件

javascript - 为什么条件在javascript中总是为真?

regex - XSS 过滤器避免表单注入(inject)匹配一个它不应该匹配的字符串