input_text = "a :01:00 pm :30:00 am ; :11:00 am, :00:00 am,: 15:00 pm : :00:00 am hay 1"
maybe it's useful to use re.sub() in conjunction with some pattern that conditions in which cases to correct the original string with a replacement
#input_text = re.compile(r"(\d{1,2})[\s|:]*(\d{0,2})\s*(am|pm)?").sub( , input_text)
One of the problems that this can have is not knowing the number of replacements that the program must perform, since the unknown input string is assumed (it may even not be necessary to perform any replacement in case no match is detected)
the output that I need,where you can see that every time I detect the pattern ":XX:00 am" where the X can be any numeric character, I replace it with "00:XX am" inside the original substring:
input_text = "a 00:01 am 00:30 am ; 00:11 am, 00:00 am,: 15:00 pm : 00:00 am hay 1"
Note that if and only if it happens, that ":01:00 pm"
then the substring "pm"
change by "am"
, when placing that they are the zero hour of the morning, remaining in the output string this "01:00 am"
, however in the case of the substring "15:00 pm"
since it does not match the regex pattern, the substring "pm"
was not changed by "am"
, remaining simply as "15:00 pm"
How to fix this regex?
CodePudding user response:
If you only care about the pattern :XX:00
and not at all about anything else around it (like the am
and pm
in your examples), this is very easy. You just need the regex pattern :(\d\d):00
and then you substitute in 00:\1
, where the \1
stands for the parenthesized group in the matching pattern.
Try this:
output_text = re.sub(r':(\d\d):00', r'00:\1', input_text)