def isNumReg(str):
regInt='\d+'#能匹配123、123.63、123eabd、abc236等所有包含了数字的字符串
regInt2='\d+$'#能匹配123、123.63、abc236等所有以数字结尾的字符串
regInt2='^\d+$'#只能匹配1、12、123等只包含数字的字符串
regFloat='\d+\.\d+'#能12.36、efa56.63、wwe56.56abc等字符串
regFloat2='^\d+\.\d+$'#能匹配2.36、0.36、00069.63、0.0、263.25等
#以下是整数和小数正确的正则表达式
regInt='^0$|^[1-9]\d*$'#不接受09这样的为整数
regFloat='^0\.\d+$|^[1-9]\d*\.\d+$'
#接受0.00、0.360这样的为小数,不接受00.36,思路:若整数位为零,小数位可为任意整数,但小数位数至少为1位,若整数位为自然数打头,后面可添加任意多个整数,小数位至少1位
regIntOrFloat=regInt+'|'+regFloat#整数或小数
patternIntOrFloat=re.compile(regIntOrFloat)#创建pattern对象,以便后续可以复用
if patternIntOrFloat.search(str):
return True
if re.search(patternIntOrFloat,str):
return True
if re.search(regIntOrFloat,str):
return True
else:
return False
if __name__=='__main__':
print isNumReg("0.360")#True
Lines 2-6 illustrate the effect of the start symbol (^) and end symbol ($).
Lines 9 and 13 illustrate that the representation of "or" in regular expressions is a vertical bar ('|')
Lines 16, 18, and 20 are equivalent to each other, that is, you can use the search method of the pattern object, or you can use the pattern object as the parameter of re.search(), or you can use the pattern string as the parameter of re.search().