regex - 使用正则表达式在字符串中查找日期

标签 regex vba excel

我正在尝试使用正则表达式在 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/

相关文章:

python - 为什么正则表达式交替 (A|B) 不按照文档匹配?

vba - Word VBA如何在两个子字符串之间选择文本并分配给变量?

c# - 使用 Interop 打印 Excel

python - 使用 pandas 读取 Excel 文件时遇到问题

javascript - 我需要获取一个输入的字符串,取出非数字字符,然后如果该字符串以1开头,则删除1

javascript - 正则表达式获取字符之间的所有字符

javascript - 未终止的正则表达式文字js错误

vba - ActiveSheet 与 Application.ActiveSheet

excel - 如果另一个单元格变为空白,则清除单元格内容

excel - 在excel中的字符串之间添加文本