Regex VBA正则表达式-从字符串抓取小时HH:MM

Regex VBA正则表达式-从字符串抓取小时HH:MM,regex,vba,excel,Regex,Vba,Excel,给定一个任意字符串,我想从该字符串抓取一个小时(HH:MM) 这是我的正则表达式: ^ # Start of string (?: # Try to match... (?: # Try to match... ([01]?\d|2[0-3]): # HH: )? # (optionally). ([0-5]?\d): # MM: (

给定一个任意字符串,我想从该字符串抓取一个小时(HH:MM)

这是我的正则表达式:

^                   # Start of string
(?:                 # Try to match...
 (?:                #  Try to match...
  ([01]?\d|2[0-3]): #   HH:
 )?                 #  (optionally).
 ([0-5]?\d):        #  MM: (required)
)?                  # (entire group optional, so either HH:MM:, MM: or nothing)
$                   # End of string
我的代码是:

Public Sub RegexTest()

 Dim oRegex As Object
 Dim time_match As Object

 Set oRegex = CreateObject("vbscript.regexp")
 With oRegex
  .Global = True
 .Pattern = "^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)$" 'HH:MM
 End With


 Dim s As String: s = "START TIME: Mar. 3rd 2016 12:00am"

 Set time_match = oRegex.Execute(s)
 If time_match.Count = 1 Then
   Debug.Print time_match.Matches(0)
 Else

 End If


End Sub
但是,我无法在这里进行匹配,也无法获得任何输出。

您的
^(?:((?:([01]?\d|2[0-3]):?([0-5]?\d):)$
模式只匹配以可选
HH:
部分开头的完整字符串,并且必须的
MM
部分后跟必须的

我建议

(?:[01]?\d|2[0-3]):[0-5]\d
因为您正在匹配字符串的一部分


请参见

删除
^
$
并使用
(?:[01]?\d|2[0-3]):[0-5]\d
模式。如果您计划重复使用此过程,那么将oRegex对象声明为静态将使您受益匪浅。有关解释和示例,请参阅。谢谢您的回答。您知道如何使用VBScript正则表达式将时间捕获到字符串中吗?匹配。匹配(0)不起作用