7

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.")
1
  • 1
    The test and the response for minimum password length don't agree. ("less than 6" is not the opposite of "more than 6")
    – trent
    Commented Oct 19, 2017 at 20:09

5 Answers 5

5

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

1

I think the regex r'(.)\1' should do what you're looking for, where \1 is a backreference.

1

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.

0

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
1
  • Could you elaborate on what all this is doing? Would something like all(pswrd[i] != pswrd[i+1] for i in xrange(len(pswrd)-1)) not be simpler?
    – ryachza
    Commented Oct 19, 2017 at 17:44
0

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

1
  • I just realised it's a bit more basic than the others
    – AJ123
    Commented Oct 19, 2017 at 17:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.