当我尝试用另一个字符串替换一个字符串时,re.sub 方法并不总是发生这种情况。
sentence = '<date>2004/12/01</date>T09:38:27+01:00'+
'Wed, <date>2012/9/05</date> 10:55:17 UTC %3C%3C%3C'
time_identifier = u'(?<=[\s\.,T])([\d]{2}[:]{1}[\d]{2}([:]{1}[\d]{2})*[\s\.,+]*(UTC|GMT|CEST|EDT|IST|BST)*(\d\d:\d\d)*)(?=[\s\.,T]|\Z)|'\
u'(?<=\A)([\d]{2}[:]{1}[\d]{2}([:]{1}[\d]{2})*[\s\.,+]*(UTC|GMT|CEST|EDT|IST|BST)*(\d\d:\d\d)*)(?=[\s\.,T]|\Z)'
time = re.search(time_identifier, sentence, flags=re.U|re.I)
if time:
try:
sentence = re.sub(time.groups()[0], '<time>%s</time>'%time.groups()[0], sentence, flags=re.U|re.I)
except:
sentence = re.sub(time.groups()[4], '<time>%s</time>'%time.groups()[4], sentence, flags=re.U|re.I)
对于上面提供的示例,我希望句子的输出是
<date>2004/12/01</date>T<time>09:38:27+01:00<time>
Wed, <date>2012/9/05</date> <time>10:55:17 UTC</time> %3C%3C%3C
但是 re.sub 方法不会将原句中的“09:38:27+01:00”替换为
"<time>09:38:27+01:00</time>"
任何人都可以请澄清原因吗?