how can I substitute a date using compile_obj.subn?

1

I do this

  for fich in ficheros:
            coincidencias = re.search(patron, fich)             
            #print(coincidencias)
            if coincidencias:
                print("coincide ----------------------->"+fich)

Result

CRC_recup_backup_2018_11_20_004003_1817970.bak
CRC_recup_backup_2018_11_21_004001_6027986.bak
CRC_recup_backup_2018_11_22_004001_7717997.bak
CRC_Test_backup_2018_11_16_004002_9068137.bak
coincide ----------------------->CRC_Test_backup_2018_11_17_004001_5428005.bak
coincide ----------------------->CRC_Test_backup_2018_11_18_004001_6838108.bak
coincide ----------------------->CRC_Test_backup_2018_11_19_004000_9968014.bak

I need to replace the date of those files with today's date newstr = compile_obj.subn('2018_11_22', 0) what I do not know if within the parenthesis is what I want to substitute or put the value of what I want to replace

    
asked by antoniop 22.11.2018 в 14:10
source

1 answer

1

Try the following (in the example, I replace the dates by 2020_08_09)

For this I use the regular expression (?<=_)[12]\d{3}_[01]\d_[0123]\d(?=_)

The code could be the following:

import re

regex = r"(?<=_)[12]\d{3}_[01]\d_[0123]\d(?=_)"

test_str = ("CRC_recup_backup_2018_11_20_004003_1817970.bak\n"
    "CRC_recup_backup_2018_11_21_004001_6027986.bak\n"
    "CRC_recup_backup_2018_11_22_004001_7717997.bak\n"
    "CRC_Test_backup_2018_11_16_004002_9068137.bak")

subst = "2020_08_09"

result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

Demo of the code

Demo of the regular expression

    
answered by 26.11.2018 / 11:06
source