2015-10-22 69 views
0

我想使用正则表达式在Excel中使用VBA从字符串中提取日期。使用正则表达式查找字符串中的日期

的字符串是:

Previous Month: 9/1/2015 - 9/30/2015 

或者可以这样:

Custom: 9/1/2015 - 9/30/2015 

你有什么想法,我怎么能做到这一点?我以前从未使用正则表达式。

+1

试试这个正则表达式:):[** Regex101例**](https://regex101.com/r/oI1oO6/1) – benjamin

回答

1

试试这个:

([1-9]|1[012])[/]([1-9]|[1-2][0-9]|3[01])[/](19|20)[0-9]{2} 
+0

这exption似乎我正在使用它 –

2

正则表达式是日期的好选择。你可以寻找:并检查剩余的符号:

Sub Foo() 
    Dim result() As Variant 

    result = GetDates("Previous Month: 9/1/2015 - 9/30/2015") 

    If UBound(result) Then 
     Debug.Print result(0) 
     Debug.Print result(1) 
    End If 
End Sub 

Function GetDates(str As String) As Variant() 
    Dim tokens() As String 
    tokens = Split(Mid$(str, InStr(str & ": ", ":")), " ") 

    If (UBound(tokens) = 3) Then 
     If IsDate(tokens(1)) And IsDate(tokens(3)) Then 
      GetDates = Array(CDate(tokens(1)), CDate(tokens(3))) 
      Exit Function 
     End If 
    End If 

    ReDim GetDates(0) 
End Function 
相关问题