查找字符串并相应地重新格式化

Finding String and Reformatting Accordingly

我一直在研究一个 VBScript,它可以找到所有具有特定扩展名 .dat 的文件,搜索特定模式,"Date Due:\d{8}",并以特定格式移动字符串。

我在使用以下代码时遇到了两个问题:

我希望这是有道理的,这是一个非常具体的脚本,但我希望在理解这里的问题时得到一些帮助。

下面是我的代码:

Set fso = CreateObject("Scripting.FileSystemObject")

'newtext = vbLf & "Date Due:" & sub_month & sub_day & sub_year 'the text replacing Date Due:

'the purpose of this script is to format the date after Date Due:, which is currently formatted as YYYYMMDD, to MM/DD/YYYY
'example: Date Date:20180605 should be Date Due:06/05/2018
Set re = New RegExp
re.Pattern = "(\nDate Due:\d{8})" 'Looking for line, Date Due: followed by 8 digits
Dim sub_str 'substring of date due, returns the 8 digits aka the date 12345678
Dim sub_month
Dim sub_day
Dim sub_year
Dim concat_full
re.Global = False
re.IgnoreCase = True

For Each f In fso.GetFolder("C:\Users\tgl\Desktop\TestFolder\").Files
    If LCase(fso.GetExtensionName(f.Name)) = "dat" Then
        text = f.OpenAsTextStream.ReadAll
        sub_str = Mid(text, 10, 8) 'substring of the full line, outputs the 8 digit date
        sub_month = Mid(sub_str, 5, 2) 'substring of the date, outputs the 2 digit month
        sub_day = Mid(sub_str, 7, 2) 'substring of the date, outputs the 2 digit day
        sub_year = Mid(sub_str, 1, 4) 'substring of the date, outputs the four digit year
        newtext = vbLf & "Date Due:" & sub_month & "/" & sub_day & "/" & sub_year 'replaces the text pattern defined above and concatenates the substrings with slashes
        'concat_full = (sub_month & sub_day & sub_year)
        f.OpenAsTextStream(2).Write re.Replace(text, newtext)
    End If
Next

编辑:re.Global 更改为 True 时,它会用找到的模式替换每一行。它应该使用每个找到的模式,而不是它找到的第一个模式。

使您的正则表达式更具体并使用捕获组来提取相关的子匹配项:

re.Pattern = "(\nDate Due:)(\d{4})(\d{2})(\d{2})"

然后像这样替换匹配项:

re.Replace(text, "//")
替换字符串中的

</code> 到 <code> 是对模式中捕获组的反向引用(即,它们被相应的捕获子字符串替换)。