StealthRT StealthRT - 6 months ago 21
Vb.net Question

RegEX to find out if there are more than 1 time and then format

Could anyone come up with a regex on how to determine if a schedule time has 2 times in it or not?

Example:

12:01 AM-3:00 AM 4:00 AM-9:00 AM
12:00 AM-5:00 AM 10:00 AM-2:00 PM
4:00 PM-7:00 PM
10:30 AM-4:00 PM
2:00 PM-5:00 PM 6:01 PM-8:01 PM
5:00 PM-6:30 PM 7:01 PM-9:46 PM
4:00 PM-10:45 PM


What I am trying to ultimately do is take out the spaces between PM's and AM's and get both times if it has more than 1 time resulting like this - placing a | between those that have more than 1 time, lowercase the AM/PM and lastly remove the space between:

12:01pm-3:00am|4:00am-9:00am
12:00am-5:00am|10:00am-2:00pm
4:00pm-7:00pm
10:30am-4:00pm
2:00pm-5:00pm|6:01pm-8:01pm
5:00pm-6:30pm|7:01pm-9:46pm
4:00pm-10:45pm


I am currently not able to think of how to go about doing that without messing up finding the 2nd set of times. I can always do:

Regex.Replace(myTimeStr, "\s", "").toLower


But doing that would combine both times if there are more than 1...

Answer

I think its better to use two replace here. You can do this

Dim pattern1 As String =  "(?<=\d)\s+(?=[AP])"
Dim pattern2 As String = "(?<=M)\s+(?=\d)"

Dim rgx1 As New Regex(pattern1)
Dim rgx2 As New Regex(pattern2)

Dim input As String = "12:01 AM-3:00 AM 4:00 AM-9:00 AM 4:00 AM-9:00 AM"

Dim result As String = rgx2.Replace(rgx1.Replace(input, ""), "|").toLower

Ideone Demo