Reputation: 6762
I am trying to Check if the input is in this pattern : MH12
Starting two digits to be MH then next two digits to be any number
and The full string should be 4 digits only. so Tired with regex = r'^[MH]\d{2}.{,4}$'
import re
def checkingInput():
while True:
try:
inp = raw_input()
if re.match(r'[MH]\d{2}', inp):
print "Thanks for your Input:",inp
break
else:
print('Invalid office code, please enter again :')
except ValueError:
print('Value error! Please try again!')
checkingInput()
but the above program even for input = MH12 it it showing Invalid Office code. Why so?
May be I am missing something?
Upvotes: 1
Views: 69
Reputation: 3506
As you're using MH as a part of the string you're trying to match, you have to exclude the [] class from your expression, so the valid one is
import re
def checkingInput():
while True:
try:
inp = raw_input()
if re.match(r'MH\d{2}', inp):
print inp
else:
print('Invalid office code, please enter again :')
except ValueError:
print('Value error! Please try again!')
checkingInput()
Upvotes: 1
Reputation: 88378
The pattern [MH]
matches exactly one letter: either an M
or an H
.
You should use MH
instead.
The entire regex is MH\d\d
; in Python syntax that would be r'MH\d\d'
.
Upvotes: 4