1

I want to make a password checker but how do I make it so I can write an error if there are characters other than digits, upper/lowercase and (,),$,%,_/.

What I have so far:

import sys
import re
import string
import random

password = input("Enter Password: ")
length = len(password)
if length < 8:
    print("\nPasswords must be between 8-24 characters\n\n")
elif length > 24:
    print ("\nPasswords must be between 8-24 characters\n\n")

elif not re.match('[a-z]',password):
        print ('error')
7
  • 2
    regexone.com Commented Oct 17, 2017 at 20:29
  • Are you asking how to write a regex that matches the conditions you set? Commented Oct 17, 2017 at 20:35
  • 1
    This is a very helpful tool: regex101.com Commented Oct 17, 2017 at 20:36
  • You should learn the basics of regexes first. Open up your favourite search engine and search for something like "regex tutorial". Commented Oct 17, 2017 at 20:36
  • 1
    Here's a link that might be related to your question, stackoverflow.com/questions/41117733/… Commented Oct 17, 2017 at 20:38

4 Answers 4

3

You need to have a regular expression against which you will validate like this:

m = re.compile(r'[a-zA-Z0-9()$%_/.]*$')
if(m.match(input_string)):
     # Do something...
else:
     # Reject with your logic ...
Sign up to request clarification or add additional context in comments.

Comments

1

Try

elif not re.match('^[a-zA-Z0-9()$%_/.]*$',password):

I can't tell if you want to allow commas. If so use ^[a-zA-Z0-9()$%_/.,]*$

Comments

1

If you want to avoid using RegEx, you can try this self-explanatory solution

allowed_characters=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0','(',')','$','%','_','/']

password=input("enter password: ")
if any(x not in allowed_characters for x in password):
  print("error: invalid character")
else:
  print("no error")

2 Comments

Very nice when you have few allowed characters and don't want to use RegEx. Thanks.
I would just replace allowed_characters with the built-in module import string where you can use allowed_characters = string.ascii_letters + string.digits + r'()$%_/.]*$' to be more readable.
0

With Python, you should be raising exceptions when something goes wrong:

if re.search(r'[^a-zA-Z0-9()$%_]', password):
    raise Exception('Valid passwords include ...(whatever)')

This searches for any character in the password that is not (^) in the set of characters defined between the square brackets.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.