- 使用正则表达式,拆解年月日
import re
'''用户输入一串日期,可能是以空格、横线等作为年月日的分割,需要将其输入的年月日分别提取出来'''
def dateSplit(date):
date1=re.sub(r'\D',"",date)
if(len(date1)!=8):
print("请输入正确的日期格式,数字部分保证8位。")
exit()
p=re.compile(r'(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})')
d=p.match(date1).groupdict()
print("您输入的日期为:"+d['year']+"年"+d['month']+"月"+d['day']+"日")
date=input("请输入年月日:")
dateSplit(date)
- 匹配0-999任意数字
import re
'''输入一个数字,判断是否在0-999之间,如果用户输入以0开头,需要将0 去掉'''
def numMatch(n):
n0=re.sub(r'\D',"",n)
p=re.compile(r'^\d{1,3}$')
p1=re.compile(r'^[0]*$')
if(p1.match(n0)):
n1='0'
else:
n1=re.sub('^[0]*',"",n0)
print(n1)
if(p.match(n1))!=None:
print("您所输入的数字"+n+"在0-999之间")
else:
print("您所输入的数字"+n+"不在0-999之间,请重新输入")
n=input("请输入一个数字:\n")
numMatch(n)