0

I want to change the following string

^mylog\.20151204\-\d{2}\:\d{2}\:\d{2}\.gc\.log\.gz$

to this:

^mylog\.2015-12-04\-\d{2}\:\d{2}\:\d{2}\.gc\.log\.gz$

(20151204 changed to 2015-12-04 only)

I can accomplish it by:

re.sub("20151204", "2015-12-04", string)

where

string= ^mylog\.20151204\-\d{2}\:\d{2}\:\d{2}\.gc\.log\.gz$

But the value 20151204 is a date and will change and I can't have it hardcoded.

I tried:

re.sub("2015\\d{2}\\d{2}", "2015\-\\d{2}\-\\d{2}", string)

However this did not work.

2 Answers 2

1

You need to use capture groups in the pattern and backreferences in the replacement:

result = re.sub("2015(\\d{2})(\\d{2})", "2015-\\1-\\2", string)
                     ^      ^^      ^         ^^^ ^^^   
// => ^mylog\.2015-12-04\-\d{2}\:\d{2}\:\d{2}\.gc\.log\.gz$

See IDEONE demo

If you need to match any year after ^mylog\., you can use

result = re.sub(r"^\^mylog\\\.(\d{4})(\d{2})(\d{2})", r"^mylog\.\1-\2-\3", string)

See another demo

Sign up to request clarification or add additional context in comments.

Comments

0

You first need to find the date and then convert it into the required format and then replace the new string in your old text.

See the code below:

 text = "^mylog\.20151204\-\d{2}\:\d{2}\:\d{2}\.gc\.log\.gz$"
 search = re.search(r'\d{4}\d{2}\d{2}',text)
 search = search.group()

you get search as:

20151204

Now create the date as you want:

 new_text = search[0:4] + "-" + search[4:6] + "-" + search[6:8]

So new_text will be:

2015-12-04

Now substitute this new_text in place of the earlier string using `re.sub()

  text = re.sub(search,new_text,text)

So now text will be:

^mylog\.2015-12-04\-\d{2}\:\d{2}\:\d{2}\.gc\.log\.gz$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.