-4

I have a task i need some help with. The task is to create a python script that asks the user to enter a desired username. The username has to be as following: "a11aaaaa". So starting with a letter, 2x numbers, 5x letters. This is the rule for how the username should look and if the given input does not match that, the user shall be able to try again until getting it right. Thankful for any help!

Robin K
  • 35
  • 5

4 Answers4

0
^\w{2}\d{2}\w{5}$   

You can use this handy site to experiment with regex: https://regex101.com/

0

You can do something like that:

import re

while True:
    name = input('Enter your name')
    if re.match('^\w\d{2}\w{5}$', name):
        break
0

Try this one:

import re

uname = input("Enter your username: ")
regex = re.compile(r"^[A-Za-z]{1}\d{2}[A-Za-z]{5}$")
if regex.findall(uname):
    print ("Valid username")
else:
    print ("Invalid username")
YusufUMS
  • 1,506
  • 1
  • 12
  • 24
  • Tried this but i can still enter for example: a18aaaa1, and i still get "valid username". – Robin K Apr 12 '19 at 12:14
  • I edited the regex, but it accommodates the capital letter. If you want to ignore the capital letter then change `[A-Za-z]` to `[a-z]` – YusufUMS Apr 12 '19 at 12:49
0

As I recently learnt from another user on SO, \w includes \d. Therefore, '^\w\d{2}\w{5}$', as suggested by some users here, will match, for example, 12345678.

To fix that, just specify the character class explicitly:

import re

regex = re.compile('^[A-Za-z]\d{2}[A-Za-z]{5}$')

while True:
    password = input('Please enter a password: ')
    if regex.search(password):
        print('Yay! Your password is valid!')
        break

    else:
        print("Oh no, that's not right. You need a letter, then two numbers, then five letters. ", end='')
gmds
  • 19,325
  • 4
  • 32
  • 58