簡體   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