【问题标题】:Identify if there are two of the same character adjacent to eachother确定是否有两个相同的字符彼此相邻
【发布时间】:2018-03-31 19:53:39
【问题描述】:

有人要求我创建一个程序来识别密码是否有效。我正在努力解决的一个问题是确定是否有两个相同的字符彼此相邻。我们将不胜感激,这是迄今为止的程序:

import re

pswrd = input("Enter Desired Password:")

if len(pswrd) < 6:
    print("Password must have more than 6 characters.")
if len(pswrd) > 15:
    print("Password must have no more than 15 characters.")
if re.search("[$#@]",pswrd):
    print("Password must have no special characters.")
if not re.search("[0-9]",pswrd):
    print("Password must contain a number.")
if not re.search("[a-z]",pswrd):
    print("Password must contain a lower case letter.")
if not re.search("[A-Z]",pswrd):
    print("Password must contain an upper case letter.")

【问题讨论】:

  • 最小密码长度的测试和响应不一致。 (“小于6”不是“大于6”的反义词)

标签: python regex python-3.x


【解决方案1】:

我认为正则表达式 r'(.)\1' 应该可以满足您的需求,其中 \1 是反向引用。

【讨论】:

    【解决方案2】:

    一种方法是使用anyall 函数:

    pswrd = input("Enter Desired Password:")
    if any(all(b[0] == b[i] for i in range(len(b))) for b in [[pswrd[c], pswrd[c+1]] for c in range(len(pswrd)-1)]):
       pass
    

    【讨论】:

    • 你能详细说明这一切是做什么的吗?像all(pswrd[i] != pswrd[i+1] for i in xrange(len(pswrd)-1)) 这样的东西会不会更简单?
    【解决方案3】:

    您可以使用反向引用和捕获组。

    (.)\1
    

    如果有两个相同的字符彼此相邻,这将匹配。

    对于两个以上的字符,您可以使用以下字符。

    (.)\1+
    

    查看here

    【讨论】:

      【解决方案4】:

      您可以将list() 密码放入列表并执行以下操作:

      pswrd = 'assdfds'
      pswrd = list(pswrd)
      for i in range(len(pswrd)):
          try:
              if pswrd[i] == pswrd[i+1]:
                  a = True
                  break
          except IndexError:
              a = False
              break
          else:
              continue
          a = False
      print(a)
      

      返回True,如果存在相邻的两个字母相同的点,则返回False

      【讨论】:

      • 我刚刚意识到它比其他人更基本
      【解决方案5】:

      检查相邻字符的正则表达式是

      (.)\1
      

      句点 (.) 匹配任何字符。方括号围绕该字符创建一个捕获组,然后由 \1 引用。

      所以,条件是:

      if re.search(r"(.)\1", pswrd)
      

      注意正则表达式前面的 r 字符。这使它成为一个 原始字符串。 正则表达式应该始终是原始字符串。这确保了正则表达式中的某些特殊字符(如 \b)在传递给 re 模块之前不会被解释。

      您可以在这里测试正则表达式:http://regexr.com/3h0g0

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-12-28
        • 2018-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-05
        相关资源
        最近更新 更多