Java教程

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

本文主要是介绍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\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)


这篇关于10. 调整字符串中文本的格式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!