例如,某软件的log文件中的日期格式为yyyy-mm-dd
:
2019-05-21 10:39:26 status unpacked python3-pip:all 2019-05-23 10:49:26 status half-configured python3 2019-05-23 10:52:26 status installed python3-pip:all 2019-05-24 11:57:26 configure python3-wheel:all 0.24 ...
要求:将日期格式改为mm/dd/yyyy
。
解决方案:使用正则表达式re.sub()
方法做字符串替换,利用正则表达式的捕获组捕获每个部分内容,在替换字符串中调整各个捕获组的顺序。
re.sub()
方法:re.sub(pattern, repl, string, count=0, flags=0)
pattern:匹配的正则表达式 string:要匹配的字符串 flags:标记为,用于控制正则表达式的匹配方式。如:是否区分大小写,多行匹配等等 repl:替换的字符串,也可作为一个函数 count:模式匹配后替换的最大次数,默认0表示替换所有匹配
返回通过正则替换后的字符串。如果pattern
没有找到,则不加改变地返回string
。
import re# f = open('/var/log/messages')# log = f.read()log = ''' 2019-05-21 10:39:26 status unpacked python3-pip:all 2019-05-23 10:49:26 status half-configured python3 2019-05-23 10:52:26 status installed python3-pip:all 2019-05-24 11:57:26 configure python3-wheel:all 0.24 '''answer = re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', log)# answer = re.sub(r'(?P\d{4})-(?P\d{2})-(?P\d{2})', r'\g/\g/\g', log)print(answer)05/21/2019 10:39:26 status unpacked python3-pip:all #结果05/23/2019 10:49:26 status half-configured python305/23/2019 10:52:26 status installed python3-pip:all05/24/2019 11:57:26 configure python3-wheel:all 0.24
当分组很多时,可以给分组起别名:
re.sub(r'(?P\d{4})-(?P\d{2})-(?P\d{2})', r'\g/\g/\g', log)