2016-12-30 29 views
1

我想检查输入是在此模式中正确地检查这个表达式:MH12如何使用python

开始两位数字是MH则接下来的两个数字中的任意数 和满弦应该只有4位数字。与regex = r'^[MH]\d{2}.{,4}$'

进口重新

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() 

但上述方案甚至对于输入那么累= MH12它它表示无效的办公室代码。为什么这样?

可能是我错过了什么吗?

+1

应r'MH \ d {2}' – e4c5

+0

我认为它应该是'如果re.match(r'MH \ d {2} $',inp):',或者在Python 3.4+中使用'r.MH \ d {2}''带're.fullmatch'。 –

+0

@ e4c5是的非常感谢! –

回答

4

图案[MH]匹配一个字母:要么一个M一个H

您应该改用MH

整个正则表达式是MH\d\d;在Python语法中将是r'MH\d\d'

+0

非常感谢 –

1

当你使用MH为你想匹配字符串的一部分,你必须从你的表情排除[]类,因此有效的一个是

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() 
1

试试吧:

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