我正在尝试使用正则表达式在 Excel 中使用 VBA 从字符串中提取日期。
字符串是:
Previous Month: 9/1/2015 - 9/30/2015
或者它可以是:
Custom: 9/1/2015 - 9/30/2015
你知道我怎么能做到这一点吗?我以前从未使用过正则表达式。
最佳答案
RegEx 对于日期来说是一个糟糕的选择。您可以寻找 :
并检查剩余的 token :
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
关于regex - 使用正则表达式在字符串中查找日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33277932/