考虑 :-
import re
def sub(matchobj):
if matchobj.group(0) == ';':
return ':'
elif matchobj.group(0) == 'a.m.':
return 'AM'
elif re.match('\\s+$', matchobj.group(0)):
return ' '
print re.sub(';|\\s+|a.m.', sub, '10; a.m. ;')
样品运行:-
C:\>python st.py
10:AM
或者也许(从 Ammar 借用我喜欢简洁的解决方案:) :-
import re
mydict = {"\s+":" ", ";":",", "a.m":"AM","x":"y"}
def sub(matchobj):
for k, v in mydict.iteritems():
if re.match('%s$' % k, matchobj.group(0)):
return v
print re.sub('|'.join(mydict.keys()), sub, 'M-Th 5:30 am-10 pm; F 5:30 a.m-10:30 p.m, Sa 10:30-10:30, Su 10:30-10 x y z x')
哪个也有效:-
C:\>python st.py
M-Th 5:30 am-10 pm, F 5:30 AM-10:30 p.m, Sa 10:30-10:30, Su 10:30-10 y y