Reputation: 129
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.")
Upvotes: 7
Views: 4698
Reputation: 656
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
Upvotes: 5
Reputation: 194
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
Upvotes: 0
Reputation: 2150
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.
Upvotes: 1
Reputation: 71451
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
Upvotes: 0
Reputation: 4540
I think the regex r'(.)\1'
should do what you're looking for, where \1
is a backreference.
Upvotes: 1