I was able to write a regex to validate the below criterias for an input box.
Regex -> ^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[+=!@#$%^&*])(?=\\S+$).{14,}$
However, this regex allows other special characters which are not mentioned. I want to restrict all the special characters except these +=!@#$%^&*
could someone help me to modify the given regex with the above criteria?
Instead of . that allows any character you can use a character set to restrict the allowed characters to a specific set:
^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[+=!@#$%^&*])(?=\\S+$)[0-9A-Za-z+=!@#$%^&*]{14,}$
Why not use sets instead of a regular expression:
import string
upperSet = set(string.ascii_uppercase)
lowerSet = set(string.ascii_lowercase)
numberSet = set("0123456789")
specialSet = set("+=!@#$%^&*")
allSets = [upperSet,lowerSet,numberSet,specialSet]
validSet = set().union(*allSets)
isValid = len(pw)>=14 and validSet.issuperset(pw) \
and all(s.intersection(pw) for s in allSets)
You could also use the translate method to convert each group of character into four codes that you then check to be exactly present in the translated string:
validCheck = str.maketrans(string.ascii_letters + "0123456789" + "+=!@#$%^&*",
"1"*26+"2"*26+"3"*10+"4"*10)
isValid = len(pw)>=14 and set('1234') == set(pw.translate(validCheck))))