[Python] 正则表达式
如题:
import re text="Guido will be out of the office from 12/15/2012 - 1/3/2013" #日期的正则表达式模式 datepat = re.compile(‘(\d+)/(\d+)/(\d+)‘) #找到并打印所有日期 for m in datepat.finditer(text): print(m.group()) #以不同方式打印日期 monthnames=[None,‘Jan‘,‘Feb‘,‘Mar‘,‘Apr‘,‘May‘,‘Jun‘,‘Jul‘,‘Aug‘, ‘Sep‘,‘Oct‘,‘Nov‘,‘Dev‘] for m in datepat.finditer(text): print("%s %s, %s" % (monthnames[int(m.group(1))],m.group(2),m.group(3))) #将所有日期替换为(日/月/年) def fix_date(m): return "%s/%s/%s" % (m.group(2),m.group(1),m.group(3)) newtext = datepat.sub(fix_date,text) #另一种方法 newtext = datepat.sub(r‘\2/\1/\3‘,text)19 print(newtext)
结果:
12/15/2012
1/3/2013
Dev 15, 2012
Jan 3, 2013
Guido will be out of the office from 15/12/2012 - 3/1/2013
相关推荐
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
夜斗不是神 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16
坚持是一种品质 2020-11-16
染血白衣 2020-11-16
huavhuahua 2020-11-20
meylovezn 2020-11-20
逍遥友 2020-11-20
weiiron 2020-11-16