Замена ввода значения текстовой функции в текстовый файл не работает - PullRequest
1 голос
/ 28 марта 2020

Это мой expiration.txt файл:

foo1; 2020-03-01 13:33;
foo2; 2020-02-01 08:45;
foo3; 2020-01-01 11:30;

Мне нужно открыть файл expiration.txt и заменить все значения даты на:

  1. 2020-03-01 13: 33 до 2020-03-01
  2. 2020-02-01 08:45 до 2020-02-01
  3. 2020-01-01 11: 30 до 2020-01-01

Я пробовал этот код безуспешно, потому что замена не работает.

Const ForReading = 1
Const ForWriting = 2
' create object
set oFSO = CreateObject("Scripting.FileSystemObject")
' open the input file
set oInFile = oFSO.OpenTextFile("expiration.txt", 1)
str_input = ""
' for each line in the input file
do while not oInFile.AtEndOfStream
  ' read the line
  str_input = trim(oInFile.ReadLine())
  Wscript.echo str_input
  ' if date found then exit the loop
     if isDate(str_input) then
        WScript.echo "Date in file found: '" & str_input & "'"
        strNewText = Replace(str_input, left(str_input, 10))    
        Set objFile = oFSO.OpenTextFile("expiration.txt", 2)
        objFile.WriteLine strNewText
        WScript.echo "Date in file found: '" & strNewText & "'"
        exit do
     end if  
loop
' close the input file
oInFile.close
' release object from memory
set oFSO = nothing

Как решить эту проблему?

1 Ответ

1 голос
/ 28 марта 2020

Использование регулярного выражения

Const ForReading = 1
Const ForWriting = 2
' create object
Set oFSO = CreateObject("Scripting.FileSystemObject")
str_input = ""
' open the input file
Set oInFile = oFSO.OpenTextFile("expiration.txt", 1)
' read the file contents
str_input = oInFile.ReadAll()
' close the input file
oInFile.Close

' use regular expression to find and replace text
Set oRegEx = CreateObject("VBScript.RegExp")
With oRegEx
    .Multiline = True
    .Global = True
    .Pattern = "(\d+)-(\d+)-(\d+)\s(\d+):(\d+);" 'will match entire date including ;
End With
str_input = oRegEx.Replace(str_input, "$1-$2-$3;")

' open the input file to overwrite
Set oInFile = oFSO.OpenTextFile("expiration.txt", 2)
oInFile.Write str_input
' close the input file
oInFile.Close
' release object from memory
set oFSO = nothing
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...