0

I'd like to use a try/except statement for checking that a string consists of letters only. What is wrong with the following

class LetterError(Exception):
    pass

name = ""
while name=="":
    try:
        x = re.match(r'[a-zA-Z]',(input("Please enter a name: ")))
        raise LetterError
    except LetterError :
        print("Insert letters only")
blubberdiblub
  • 4,085
  • 1
  • 28
  • 30
monika
  • 3
  • 2

2 Answers2

0

Your regex [a-zA-Z] will match only one character out of given range [a-zA-Z].

I suppose by name you mean multiple characters. Thus use [a-zA-Z]+ for matching multiple characters.

Rahul
  • 2,658
  • 12
  • 28
-1

You are raising error in all case. You need to add a condition and also, you don't need your custom error. Regex from here https://stackoverflow.com/a/3617808/5567387

name = ""
while name == "":
    name = raw_input("Please enter a name: ")
    is_valid = re.match(r'^[a-zA-Z]+$', name)
    if not is_valid:
        name = ""
Community
  • 1
  • 1
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
  • Have you tested it? There are multiple issues. – yeniv May 02 '17 at 10:17
  • The OP wanted to check if a string consists of letters only. The current solution would accept if the string has numbers in it e.g. if it is `abcd345` or `abcd5efgh`. – yeniv May 02 '17 at 10:33