I need a regular expression for python 2.7 that checks if a given word consists only of the letters 'a', 'b', 'r', 'e', 'd'. Please Help!
I tried the following code:
text = raw_input ('Enter Text:')
result = re.match(r'[abred]+', text)
if result:
print ('Match')
else :
print ("Doesn't Match")
However, for example by inputting "aaaq" it counts it as a matching text.
In order to modify your regex to work you need to use the ^
and $
characters. ^
matches the beginning of the string, and $
matches the end of the string. So if you were to modify your regex to be ^[abred]+$
it would match strings that only contained the letters a
, b
, r
, e
, and d
. As opposed to the current regex ([abred]+
), which will match any string that had those letters in it.