2016-08-22 17 views
2

任意の文字列を指定すると、文字列から1時間(HH:MM)を取得したいと考えています。VBA正規表現 - グラブ時間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 

は、しかし、私はここに一致し、何も出力を取得しないことができません

は、ここに私の正規表現です。

+3

削除を参照してください '^'と '$'と '使用(:[01] \ D | 2 [0-3]??):[0-5] \ D 'のパターン。 https://regex101.com/r/wQ4mK9/1 –

+0

を参照してください。この手順を繰り返し使用する場合は、** oRegex **オブジェクトを** Static **と宣言すれば恩恵を受けるでしょう。説明と例については、[静的変数を使用するタイミング](http://stackoverflow.com/documentation/vba/877/declaring-variables/16978/when-to-use-a-static-variable)を参照してください。 – Jeeped

答えて

3

あなた^(?:(?:([01]?\d|2[0-3]):)?([0-5]?\d):)$パターンは、オプションのHH:一部で始まる完全な文字列と一致し、及び義務MM一部が義務付け:と続きます。

あなたは文字列の一部に一致しているので、私は

(?:[01]?\d|2[0-3]):[0-5]\d 

を示唆しています。

regex demo

+0

答えをありがとう。あなたはVBScriptの正規表現を使用して文字列に時間をキャプチャする方法を知っていますか? match.Matches(0)は機能しません – BDillan

+1

マッチは気にしません.Item(0).Value – BDillan