3

I have the following requirement to validate the password with below context

  • at least one digit
  • at least one uppercase letter
  • at least one lowercase letter
  • at least one special character[$@#]

Below program is doing the partial match but not the full regex

#!/usr/sfw/bin/python
import re
password = raw_input("Enter string to test: ")
if re.match(r'[A-Za-z0-9@#$]{6,12}', password):
    print "match"
else:
    print "Not Match"

In use:

localhost@user1$ ./pass.py
Enter string to test: abcdabcd
match

It is evaluating the wrong output. Can anyone suggest here should I use re.search?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
user216358
  • 65
  • 1
  • 1
  • 5
  • `'abcdabcd'` *does* match your regular expression, it has between 6 and 12 characters in the list of valid characters. – jonrsharpe Oct 05 '17 at 09:48
  • only Valid inputs are like abcd123A#, abcd123A$, abcd123A@. it should not accept any other input as abcd233AA#*. see below output localhost@user1$ ./pass.py Enter string to test: abcd233AA#* match – user216358 Oct 05 '17 at 09:53
  • And those *also* match the regex, but the expression you've written **does not** enforce your list of requirements. – jonrsharpe Oct 05 '17 at 09:55
  • can you suggest me the regex to enforce the requirements ? – user216358 Oct 05 '17 at 09:59
  • You might also want to check out https://stackoverflow.com/questions/45878324/how-to-check-if-string-has-lowercase-letter-uppercase-letter-and-number/ and possibly use/adapt one of the solutions there... – Jon Clements Oct 05 '17 at 12:38

1 Answers1

11

Here is the Regex for at least one digit, one uppercase letter, at least one lowercase letter, at least one special character

import re
password = input("Enter string to test: ")
# Add any special characters as your wish I used only #@$
if re.match(r"^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[@#$])[\w\d@#$]{6,12}$", password):
    print ("match")
else:
    print ("Not Match")

Hope this will Help You...

Muthu Kumar
  • 885
  • 2
  • 14
  • 25
  • localhost@user1$ ./pass.py Enter string to test: abcd123A# Not Match it is failed Only allowed special chacter are $,@ and # – user216358 Oct 05 '17 at 10:11
  • 2
    @MuthuKumar replace `.+` inside each lookaheads with `.*` , in the above regex, first lookahead expects a char to be present before the digit. But in this example `2abcdjgA#`, there isn't any char before 2. So it would fail. – Avinash Raj Oct 05 '17 at 12:29