Shivkumar kondi
Shivkumar kondi

Reputation: 6762

How to properly check this regex using python

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

Answers (3)

super.single430
super.single430

Reputation: 254

try it:

re.findall(r'MH\d{2}', s)

Upvotes: 1

dmitryro
dmitryro

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

Ray Toal
Ray Toal

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

Related Questions