Regex, how to remove all non-alphanumeric except colon in a 12/24 hour timestamp?
python, regex
Solution
# this: D:DD, DD:DDam/pm 12/24 hr
re = r':(?=..(?<!\d:\d\d))|[^a-zA-Z0-9 ](?<!:)'
A colon must be preceded by at least one digit and followed by at least two digits: then it's a time. All other colons will be considered textual colons.
How it works
: // match a colon
(?=.. // match but not capture two chars
(?<! // start a negative look-behind group (if it matches, the whole fails)
\d:\d\d // time stamp
) // end neg. look behind
) // end non-capture two chars
| // or
[^a-zA-Z0-9 ] // match anything not digits or letters
(?<!:) // that isn't a colon
Then when applied to this silly text:
Today, 3:30pm - Group 1,2,3 Meeting to di4sc::uss3: 2:3:4 "big idea" on 03:33pm or 16:47 is also good
...changes it into:
Today, 3:30pm Group 123 Meeting to di4scuss3 234 big idea on 03:33pm or 16:47 is also good
Problem
I have a string like: ``` Today, 3:30pm - Group Meeting to discuss "big idea" ``` How do you construct a regex such that after parsing it would return: ``` Today 3:30pm Group Meeting to discuss big idea ``` I would like it to remove all non-alphanumeric characters except for those that appear in a 12 or 24 hour time stamp.