简体   繁体   中英

Identify if there are two of the same character adjacent to eachother

I've been asked to create a program that identifies if a password is valid or not. The one part I am struggling with is identifying whether there are two of the same character adjacent to each other. Help would be appreciated and here is the program so far:

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.")

The regex to check for adjacent characters is

(.)\1

The period (.) matches any character. The brackets create a capturing group around that character, which is then referenced by \\1.

So, the condition would be:

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

Note the r character before the regular expression. This makes it a raw string. Regular expressions should always be made raw strings. This ensures that certain special characters in the regex (like \\b) are not interpreted before being passed to the re module.

You can test the regular expression here: http://regexr.com/3h0g0

我认为正则表达式r'(.)\\1'应该做你想要的,其中\\1是反向引用。

One way is to use the any and all functions:

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

You could use backreferences and capture group.

(.)\1

This would match if there are two of the same character adjacent to each other.

For more than two characters you could use the following.

(.)\1+

Check it out here .

You could list() the password into a list and do this:

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)

This returns True, it returns False if there are points in which two letters adjacent to each other are the same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM