替换txt文件中输入的文本函数值不起作用 [英] Replacing text function value input in txt file not work

查看:20
本文介绍了替换txt文件中输入的文本函数值不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 expiration.txt 文件:

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

我需要打开 expiration.txt 文件并替换以下所有日期值:

I need open the expiration.txt file and replace the all date value from:

  1. 2020-03-01 13:332020-03-01
  2. 2020-02-01 08:452020-02-01
  3. 2020-01-01 11:302020-01-01
  1. 2020-03-01 13:33 to 2020-03-01
  2. 2020-02-01 08:45 to 2020-02-01
  3. 2020-01-01 11:30 to 2020-01-01

我试过这段代码没有成功,因为替换不起作用.

I have tried this code without success, because the replace not working.

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

如何解决这个问题?

推荐答案

使用正则表达式

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

这篇关于替换txt文件中输入的文本函数值不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆