【问题标题】:how to use variables in Regex如何在正则表达式中使用变量
【发布时间】:2019-11-08 16:09:02
【问题描述】:

我正在尝试编写一个检查强密码的函数。密码必须包含一个大写,一个小写,一个数字,并且必须是8个字符。

import re

def checker():

 while True:
   userInput = input(' Please input a password ')
   passwordRegex = re.compile(r'[a-zA-Z0-9]+ {,8}')
   match = passwordRegex.search(userInput)
   if match:
        print('Good!')
   else:
        print('Bad!')

checker()

即使密码满足所有要求,此函数也始终输出Bad。我感觉这个错误与我使用正则表达式和变量的方式有关。我正在使用python 3.6。

【问题讨论】:

  • 这与变量无关。只是 1)您的正则表达式错误,2)您使用的正则表达式错误(re.search)。
  • 请注意,您的正则表达式尝试按字面意思匹配`{,8}`
  • 感谢您的反馈@Aran-Fey,我已根据您的建议更新了我的代码。

标签: python regex


【解决方案1】:

扩展来自here的答案:

passwordRegex = re.compile("^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\S{8,}")

查看this demo

使用前瞻,我们确保每组至少有一个字符,然后总共需要至少 8 个字符。请注意,您可以通过更改最后一组,即{8,} 之前的一组来自定义允许的字符(如果您想允许符号)

【讨论】:

    【解决方案2】:

    根据@Aran-Fey 和@Tomerikoo 的反馈,我已经更新了我的代码,它现在可以工作了。

    import re
    
    def checker():
    
        while True:
    
        userInput = input(' Please input a password ')
    
        passwordRegex = re.search(r'^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$',userInput)
    
        if passwordRegex:
    
            break
    
         print('Good!')
    
    
    checker()
    

    【讨论】:

    • 这只会查找至少一个字母和至少一个数字。这意味着这个密码tomerkal9 将通过。这是你想要的吗?
    • 我正在关注一本 python 书(用 python 自动化无聊的东西),是的,这满足了练习的要求。欣赏建议:)
    猜你喜欢
    • 2017-10-11
    相关资源
    最近更新 更多