读取文本并匹配文本文件中的所有日期,否则将值写入error.txt文件

时间:2016-02-09 18:35:52

标签: vbscript

将以下.TXT文件读入VBS FileSystemObject。我正在尝试搜索所有匹配的日期,否则我需要将它们放在“error.txt”文件中。但是,当我在下面运行我的代码时,它始终将匹配放在error.txt文件中,而不是跳过匹配的日期。

为什么日期不匹配?

INPUT:

"LIRRR 1M",.412900,02/08/2016
"LIRRR 3M",.222700,02/08/2016
"LIRRR 6M",.333200,02/08/2016
"LIRRR12M",1.1333300,02/08/2016
"FEDFRRRR",.333000,02/08/2016
"CCC 1YR",.550330,02/08/2016
"5YRCMT",1.2503300,02/08/2016
"10YRCMT",1.860000,02/08/2016 

以下是我编写的代码:

On error resume next
Const ForReading = 1
Dim strSearchFor
Dim MyDate, MyWeekDay
MyDate = Date ' Assign a date.
MyWeekDay = Weekday(MyDate) 
If MyWeekDay = 2 then 
  strSearchFor =Right("0" & DatePart("m",Date), 2)&"/"&Right("0" & DatePart("d",Date-3), 2)&"/"&DatePart("yyyy",Date)
 Else 
  strSearchFor =Right("0" & DatePart("m",Date), 2)&"/"&Right("0" & DatePart("d",Date-1), 2)&"/"&DatePart("yyyy",Date)
 End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\Users\Desktop\index.txt", ForReading)
do until objTextFile.AtEndOfStream
    strLine = objTextFile.ReadLine()

    If InStr(strLine, strSearchFor) <> 0 then

    Set objFile = objFSO.CreateTextFile("C:\Users\Desktop\pass.txt")
      objFile.Write "date is  match"& vbCrLf

    Else
        Set objFile = objFSO.CreateTextFile("C:\Users\Desktop\error.txt")
      objFile.Write "date is not match"& vbCrLf
    End If
loop
objTextFile.Close

1 个答案:

答案 0 :(得分:0)

为什么不使用RegEx来获取看似日期的字符串部分并使用IsDate函数对其进行验证?

Option Explicit
Dim arrLines,i
arrLines = ReadFile("./input.txt","byline")
For i=LBound(arrLines) to UBound(arrLines)
    wscript.echo FormatOutput(arrLines(i))
Next
'*********************************************
Function FormatOutput(s)
    Dim re, match
    Set re = New RegExp
    re.Pattern = "[\d]+[\/-][\d]+[\/-][\d]+"
    re.Global = True
    For Each match In re.Execute(s)
        if IsDate(match.value) then
            FormatOutput = CDate(match.value)
            Exit For
        end if
    Next
    Set re = Nothing
End Function
'*********************************************
Function ReadFile(path,mode)
    Const ForReading = 1
    Dim objFSO,objFile,i,strLine
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(path,ForReading)
    If mode = "byline" then
        Dim arrFileLines()
        i = 0
        Do Until objFile.AtEndOfStream
            Redim Preserve arrFileLines(i)
            strLine = objFile.ReadLine
            strLine = Trim(strLine)
            If Len(strLine) > 0 Then
                arrFileLines(i) = strLine
                i = i + 1
                ReadFile = arrFileLines
            End If  
        Loop
        objFile.Close
    End If
    If mode = "all" then
        ReadFile = objFile.ReadAll
        objFile.Close
    End If
End Function
'*****************************************************************