我一直在研究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
时,它将每一行替换为一个找到的模式。它应该使用每个找到的模式,而不是找到的第一个模式。
答案 0 :(得分:1)
使正则表达式更具体,并使用捕获组来提取相关子匹配项:
re.Pattern = "(\nDate Due:)(\d{4})(\d{2})(\d{2})"
然后替换这样的匹配项:
re.Replace(text, "$1$4/$3/$2")
替换字符串中的 $1
至$4
是对模式中捕获组的反向引用(即它们被相应的捕获子字符串替换了)。