日志中的日期替换

情景:
某个日志中有大量的日期,想把日期格式调整统一
如:

.
.
12/21/2018 10:46:25 [root] WARNING: userinfo error http://guba.eastmoney.com/news,of000038,114062178.html
12/21/2018 10:46:25 [root] WARNING: userinfo error http://guba.eastmoney.com/news,of000038,148643273.html
12/21/2018 10:46:25 [root] WARNING: userinfo error http://guba.eastmoney.com/news,of000038,121724539.html
.
.

需求:
想把 12/21/2018 这种格式统一替换为 2018-12-21

s = '12/24/2018 jfeiwllf\n12/01/2018 nicai'
print(s)
import re 

l1 = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2',s)
print(l1)

实例结果:
12/24/2018 jfeiwllf
12/01/2018 nicai
2018-12-24 jfeiwllf
2018-12-01 nicai

存在隐患:

  1. 使用了正则表达式的sub方法,在使用了括号匹配,我们需要数对应的位置,\3-\1-\2 的方式去替换,但是如果() 过多,我们数起来就比较的麻烦了
l2 = re.sub(r'(?P\d+)/(?P\d+)/(?P\d+)',r'\g-\g-\g' ,s)
print(s)
print(l2)

测试结果:
12/24/2018 jfeiwllf
12/01/2018 nicai
2018-12-24 jfeiwllf
2018-12-01 nicai

发现可以结果正确了,使用了 ?P 和 \g 与之对应,就是一开始定义的时候麻烦点,但是比较好统一

你可能感兴趣的:(python,菜鸟练习)