我试图检查输入是否符合以下模式:MH12
启动两位数字为MH,然后下两位数字为任意数字,而整串应仅为4位数字。厌倦了regex = r'^[MH]\d{2}.{,4}$'
导入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()但是上面的程序,即使对于input = MH12,它也显示无效的Office代码。为什么会这样呢?
可能是我遗漏了什么?
发布于 2016-12-30 08:30:22
模式[MH]正好匹配一个字母:M或H。
您应该使用MH代替。
整个regex是MH\d\d;在Python语法中是r'MH\d\d'。
发布于 2016-12-30 08:42:50
当您使用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()发布于 2016-12-30 08:53:49
试一试:
Re.findall(r‘’MH\d{2}‘,s)
https://stackoverflow.com/questions/41393051
复制相似问题