RegEx Time function

Juggler_IN

Active Member
Joined
Nov 19, 2014
Messages
349
Office Version
  1. 2003 or older
Platform
  1. Windows
I have a RegEx Time function that extracts time values from a string.

The code extracts values but misses out on the pm in the test string: Immediate Window ?Join(Time("ABCD 10:10:10 am to 20:10:10 pm EFGH")) outputs 10:10:10 am 20:10:10.

I am unable to figure out the edits.

The function:
VBA Code:
Public Function Time(x As String)

    Dim oRegex As Object

    If oRegex Is Nothing Then
        Set oRegex = CreateObject("VBScript.RegExp")
        oRegex.Global = True
        oRegex.Pattern = "\b(0?[0-9]|1[0-2]):[0-5]\d(:[0-5]\d)?\s?(AM|PM|am|pm)\b|\b([0-9]|[0-1]\d|2[0-3]):[0-5]\d(:[0-5]\d)?(?!:)"
    End If

    Time = Empty

    If oRegex.Test(x) Then Time = Array(oRegex.Execute(x).Item(0).Value, oRegex.Execute(x).Item(1).Value)

End Function
 

Excel Facts

Excel Can Read to You
Customize Quick Access Toolbar. From All Commands, add Speak Cells or Speak Cells on Enter to QAT. Select cells. Press Speak Cells.
Does this modification work for you?
VBA Code:
Public Function Time(x As String)

    Dim oRegex As Object

    If oRegex Is Nothing Then
        Set oRegex = CreateObject("VBScript.RegExp")
        oRegex.Global = True
        oRegex.Pattern = "\b(0?[0-9]|1[0-2]):[0-5]\d(:[0-5]\d)?\s?(AM|am)\b|\b([0-9]|[0-1]\d|2[0-3]):[0-5]\d(:[0-5]\d)?\s?(PM|pm)?(?!:)"
    End If

    Time = Empty

    If oRegex.Test(x) Then Time = Array(oRegex.Execute(x).Item(0).Value, oRegex.Execute(x).Item(1).Value)

End Function
 
Upvote 0

Forum statistics

Threads
1,214,954
Messages
6,122,462
Members
449,085
Latest member
ExcelError

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top