匹配字符串vba excel中的日期模式

时间:2013-03-14 20:36:09

标签: regex excel vba

修改 由于我的字符串变得越来越复杂,看起来像是唯一的方法。 我没有太多的经验,非常感谢你的帮助。

基本上从我在网上看到的内容中,我构建了以下exp来尝试在我的示例字符串中匹配出现:

“我很长的字符串12Mar2012就在这里23Apr2015” [0-9] [0-9] + [a-zA-Z] + [0-9] [0-9] [0-9] [0-9]

并尝试此代码。我没有任何比赛。关于正则表达式教程的任何好的链接都非常赞赏。

  Dim re, match, RegExDate
    Set re = CreateObject("vbscript.regexp")
    re.Pattern = "(^[0-9][0-9] + [a-zA-Z] + [0-9][0-9][0-9][0-9]$)"
    re.Global = True

    For Each match In re.Execute(str)
        MsgBox match.Value
        RegExDate = match.Value
        Exit For
    Next

谢谢

3 个答案:

答案 0 :(得分:2)

此代码使用Regexp验证DateValue的实际日期是否具有健壮性

Sub Robust()
Dim Regex As Object
Dim RegexMC As Object
Dim RegexM As Object
Dim strIn As String
Dim BDate As Boolean
strIn = "My very long long string 12Mar2012 is right here 23Apr2015 and 30Feb2002"
Set Regex = CreateObject("vbscript.regexp")
With Regex
 .Pattern = "(([0-9])|([0-2][0-9])|([3][0-1]))(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\d{4})"
 .Global = True
If .test(strIn) Then
   Set RegexMC = .Execute(strIn)
   On Error Resume Next
   For Each RegexM In RegexMC
   BDate = False
   BDate = IsDate(DateValue(RegexM.submatches(0) & " " & RegexM.submatches(4) & " " & RegexM.submatches(5)))
   If BDate Then Debug.Print RegexM
   Next
   On Error GoTo 0
End If
End With
End Sub

答案 1 :(得分:1)

感谢您的帮助! 我设法使用这个简单的代码解决了我的问题。

Dim rex As New RegExp
Dim dateCol As New Collection
rex.Pattern = "(\d|\d\d)(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\d{4})?"
rex.Global = True

For Each match In rex.Execute(sStream)
    dateCol.Add match.Value
Next

请注意,就我而言,我确信我在字符串中获得了有效日期,因此reg表达式很容易。

日Thnx 伊利亚

答案 2 :(得分:0)

以下是我的快速尝试。它远非完美。

基本上,它将字符串拆分为单词。在循环显示单词时,它会切断任何标点符号(句点和逗号,您可能需要添加更多标点符号)。

处理项目时,我们会尝试从中删除每个月的名称。如果字符串变短,我们可能会有一个日期。

检查最终字符串的长度是否正确(5或6个字符,1或2 + 4表示日期和年份)

你可以改为(或者)检查是否有所有数字。

Private Const MonthList = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC"
Public Function getDates(ByVal Target As String) As String
Dim Data() As String
Dim Item As String
Dim Index As Integer
Dim List() As String
Dim Index2 As Integer
Dim Test As String
Dim Result As String

    List = Split(MonthList, ",")
    Data = Split(Target, " ")
    Result = ""

    For Index = LBound(Data) To UBound(Data)
        Item = UCase(Replace(Replace(Data(Index), ".", ""), ",", ""))
        For Index2 = LBound(Data) To UBound(Data)
            Test = Replace(Item, List(Index2), "")
            If Not Test = Item Then
                If Len(Test) = 5 Or Len(Test) = 6 Then
                    If Result = "" Then
                        Result = Item
                    Else
                        Result = Result & ", " & Item
                    End If
                End If
            End If
        Next Index2
    Next
    getDates = Result
End Function