Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.")
like image 508
white Avatar asked Oct 19 '17 17:10

white


People also ask

How do you check if two strings have the same character?

To check if two strings have the same characters:Use the sorted() function to sort the two strings. Use the equality operator to compare the results. If the comparison evaluates to True , the two strings have the same characters.

How do I check if two characters are the same in Python?

Python strings equality can be checked using == operator or __eq__() function. Python strings are case sensitive, so these equality check methods are also case sensitive.


1 Answers

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

like image 67
omijn Avatar answered Oct 05 '22 04:10

omijn