StealthRT StealthRT - 1 year ago 46 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?


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:


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 Source

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