Во-первых, вы можете указать квантификатор в запросах регулярных выражений, поэтому, если вы хотите 4 числа, вам не нужно [0-9][0-9][0-9][0-9]
, но вы можете сделать с [0-9]{4}
. Чтобы захватить выражение, оберните его в круглые скобки value=([0-9]{4})
даст вам только цифры
Если вы хотите использовать re.sub
, вам просто нужно дать ему скороговорку, строку замены и вашу строку ввода, например, re.sub(pattern, replacement, string)
Таким образом:
import re
txt = """ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
Date, TimeWindowStart, TimeWindowEnd, Report-20190323_210000
"""
pattern_date = 'ReportDate=([0-9]{2}/[0-9]{2}/[0-9]{4})'
report_date = re.findall(pattern_date, txt)[0]
pattern_time_start = 'TimeWindowStart=([0-9]{2}:[0-9]{2}:[0-9]{2})'
start_time = re.findall(pattern_time_start, txt)[0]
pattern_time_end = 'TimeWindowEnd=([0-9]{2}:[0-9]{2}:[0-9]{2})'
end_time = re.findall(pattern_time_end, txt)[0]
splitted = txt.split('\n') # Split the txt so that we skip the first line
txt2 = '\n'.join(splitted[1:]) # text to perform the sub
# substitution of your values
txt2 = re.sub('Date', report_date, txt2)
txt2 = re.sub('TimeWindowStart', start_time, txt2)
txt2 = re.sub('TimeWindowEnd', end_time, txt2)
txt_final = splitted[0] + '\n' + txt2
print(txt_final)
Выход:
ReportDate=03/24/2019, TimeWindowStart=18:00:00, TimeWindowEnd=20:59:59
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000
03/24/2019, 18:00:00, 20:59:59, Report-20190323_210000