import re
import time
#要进行正则匹配的原字符串
srcstr = r"http://write.bolg.csdn.python_2013_08_04_21.net"
#假如要匹配字符串中的日期和时间,然后替换为当天的
datestr = time.strftime("%Y_%m_%d_%H",time.localtime(time.time()))
#正则表达式
s = r"python_(\d{4}_(\d{2})_(\d{2})_(\d{2}))"
p = re.compile(s)
match = p.search(srcstr)
#匹配成功后使用sub,可以将匹配的正则表达式替换
if match:
deststr = p.sub(datestr,srcstr)
#当然如果我们想要获取正则表达式中的年份,或者月份、天数该怎么办?
myyear = match.group(1)
mymonth = match.group(2)
myday = match.group(3)
myhour = match.group(4)
#也有人可能好奇match.group(0)是什么?可以是试一下,是你匹配到的字符串。
myrestr = match.group(0)