简体   繁体   中英

How to replace a pattern using regular expression?

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

I would like to replace a particular pattern in a string. Output should be 2018-Feb-23-5-18-11 .

How can i do that by using re.sub ?

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

Fetching the current_datetime from datetime module. i'm formatting the obtained datetime in a desired format.

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

I thought, re.sub is the best way to do that.

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

Use the datetime module.

Ex:

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))

Output:

2018-Feb-23-5-18-11

When working with dates and times, it is almost always best to convert the date first into a Python datetime object rather than trying to attempt to alter it using a regular expression. This can then be converted back into the required date format more easily.

With regards to leading zeros though, the formatting options only give leading zero options, so to get more flexibility it is sometimes necessary to mix the formatting with standard Python formatting:

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)

Giving you:

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

This uses a .format() function to combine the parts. It allows objects to be passed and the formatting is then able to access the object's attributes directly. The only part that needs to be formatted using strftime() is the month.


This would give the same results:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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