Gio Plenzik
Gio Plenzik

Reputation: 56

re.match not working in python 2.7

keyword = "*"
keyphrase = "*"
while not(re.match('[a-z ]',keyword)):
    keyword = raw_input("enter a keyword:-").lower()
while not(re.match('[a-z ]',keyphrase)):
    keyphrase = raw_input("enter a key phrase:-").lower()

The code above is the start of a programme I am making; however I would like the keyword and keyphrase (which are raw_inputs) that the user enters to only be characters of the alphabet or spaces, therefore they must not contain other characters such as numbers or symbols.

The code above does not work fully for example, if the user enters "1234" as a keyword, the loop runs and they must enter a keyword again; the same applies for "1234abcd", however if they enter "abcd1234" the loop does not run even though it contains numbers.

Upvotes: 1

Views: 617

Answers (2)

Patrick Kostjens
Patrick Kostjens

Reputation: 5105

re.match matches from the start, but also returns matches if the match was not until the end of the text. So in your example input abcd1234, your regex matches the abcd part. Therefore your loop stops (a match is found).

Change the regex so that it matches until the end of the text, and your problem will be resolved. Try the code below:

keyword = "*"
keyphrase = "*"
while not(re.match('[a-z ]*$',keyword)):
    keyword = raw_input("enter a keyword:-").lower()
while not(re.match('[a-z ]*$',keyphrase)):
    keyphrase = raw_input("enter a key phrase:-").lower()

Note the $ means that the regex has to match until the end of the string. The * means that any number of occurrences of [a-z ] can be matched.

Upvotes: 2

Avinash Raj
Avinash Raj

Reputation: 174796

Because re.match tries to match from the start and also your regex [a-z ] matches exactly one character, ie the first one and don't care about the remaining characters.

while not(re.match('[a-z ]+$',keyword)):
    keyword = raw_input("enter a keyword:-").lower()

Upvotes: 2

Related Questions