Python: Unmatched group exception

python-2.7, regex, replace

Solution

Why have two groups in the first place?

pat1 = r"(\d+(?:[:]\d+)?)\s*am"
pat1 = r"(\d+(?:[:]\d+)?)\s*pm"

Note the use of a raw string. Otherwise you might get problems with escaping.

What did I do? I just stuff the whole time into one group, and made `:\d+` optional (with a non-capturing group). Replacement would of course be `\1 AM` and `\1 PM`.

Problem

I have the string consisting times and I wanted to format the times to 12hrs format. I tried, ``` pat1 = "(\d+):(\d+)?\s*pm" pat1 = "(\d+):(\d+)?\s*am" hooString = "673 HOO: Mon. 7:30 am - 6pm, Tue. 7:30am - 6 pm, Wed. 7:30 am - 6 pm, Thurs. 7:30 am - 6 pm, Fri. 8 am - 5 pm," hooString = sub(compile(pat1, IGNORECASE), "\1:\2 AM", hooString) hooString = sub(compile(pat2, IGNORECASE), "\1:\2 PM", hooString) print hooString ``` I got the output as, ``` 673 HOO: Mon. 7:30 AM - 6pm, Tue. 7:30 AM - 6 pm, Wed. 7:30 AM - 6 pm, Thurs. 7:30 AM - 6 pm, Fri. 8 am - 5 pm, ``` But I required "8am or 8 am" also to be replaced to "8 AM", so I slightly changed regex to ``` pat1 = "(\d+):?(\d+)?\s*am" pat2 = "(\d+):?(\d+)?\s*pm" ``` It throws me "unmatched group" exception. because of the 2nd group doesn't exists in input string. How could I get my expected result without exception for both the conditions "%H:%M %P" as well as "%H %p" Also If I could get the result for "8 am" as "8:00 AM" that could be the best answer.

Original source