10. 调整字符串中文本的格式

例如,某软件的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<Y>\d{4})-(?P<M>\d{2})-(?P<D>\d{2})', r'\g<M>/\g<D>/\g<Y>', log)
print(answer)

05/21/2019 10:39:26 status unpacked python3-pip:all             #结果
05/23/2019 10:49:26 status half-configured python3
05/23/2019 10:52:26 status installed python3-pip:all
05/24/2019 11:57:26 configure python3-wheel:all 0.24

当分组很多时,可以给分组起别名:

re.sub(r'(?P<Y>\d{4})-(?P<M>\d{2})-(?P<D>\d{2})', r'\g<M>/\g<D>/\g<Y>', log)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值