繁体   English   中英

如何使用正则表达式替换模式?

[英]How to replace a pattern using regular expression?

string1 = "2018-Feb-23-05-18-11"

我想替换字符串中的特定模式。 输出应为2018-Feb-23-5-18-11

我怎样才能通过使用re.sub做到这一点?

Example:
import re
output = re.sub(r'10', r'20', "hello number 10, Agosto 19")
#hello number 20, Agosto 19

从 datetime 模块获取 current_datetime。 我正在以所需的格式格式化获得的日期时间。

ts = time.time()
st = datetime.datetime.fromtimestamp(ts).strftime("%Y-%b-%d-%I-%M-%S")

我想,re.sub 是最好的方法。

ex1 : 
string1 = "2018-Feb-23-05-18-11"
output : 2018-Feb-23-5-18-11

ex2 : 
string1 = "2018-Feb-23-05-8-11"
output : 2018-Feb-23-5-08-11

使用日期时间模块。

前任:

import datetime

string1 = "2018-Feb-23-05-18-11"
d = datetime.datetime.strptime(string1, "%Y-%b-%d-%H-%M-%S")
print("{0}-{1}-{2}-{3}-{4}-{5}".format(d.year, d.strftime("%b"), d.day, d.hour, d.minute, d.second))

输出:

2018-Feb-23-5-18-11

在处理日期和时间时,几乎总是最好先将日期转换为 Python datetime对象,而不是尝试使用正则表达式尝试更改它。 然后可以更轻松地将其转换回所需的日期格式。

不过,关于前导零, 格式选项只提供前导零选项,因此为了获得更大的灵活性,有时需要将格式与标准 Python 格式混合:

from datetime import datetime

for test in ['2018-Feb-23-05-18-11', '2018-Feb-23-05-8-11', '2018-Feb-1-0-0-0']:
    dt = datetime.strptime(test, '%Y-%b-%d-%H-%M-%S')
    print '{dt.year}-{}-{dt.day}-{dt.hour}-{dt.minute:02}-{dt.second}'.format(dt.strftime('%b'), dt=dt)

给你:

2018-Feb-23-5-18-11
2018-Feb-23-5-08-11
2018-Feb-1-0-00-0

这使用.format()函数来组合各个部分。 它允许传递对象,然后格式化可以直接访问对象的属性。 唯一需要使用strftime()格式化的部分是月份。


这将给出相同的结果:

import re

for test in ['2018-Feb-23-05-18-11', '2018-Feb-23-05-8-11', '2018-Feb-1-0-0-0']:
    print re.sub(r'(\d+-\w+)-(\d+)-(\d+)-(\d+)-(\d+)', lambda x: '{}-{}-{}-{:02}-{}'.format(x.group(1), int(x.group(2)), int(x.group(3)), int(x.group(4)), int(x.group(5))), test)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM