功能失调的基于正则表达式的 vbscript 用于在 .c 文件中的特定位置追加多行文本

dysfunctional regex based vbscript being used to append multiple lines of text at a specific location in a .c file

我正在学习正则表达式和 vbscript,以便通过每月添加用户输入的文本来将文本追加到新行的 .c 文件中。我从我的模式中删除了 positive lookbehind assertion '?<=' 以消除我之前 post:

的语法错误

这是修改后的模式:

re.Pattern = "(loss_pct_through_([a-zA-Z]{3,5}\d{4})\[([a-zA-Z_]{1,2}\d{1,2})\]\s=\s\d\.\d{14}[;]\n)\n(?=\}\n)"

现在我有一个脚本 运行,但它不符合预期目的,因为由以下代码生成的用户输入相关文本不会附加到 .c 文件。

path = "<C:\Users\Parth\Desktop\C06S3000.C>"
set re = new regexp 

Set objfso = CreateObject("Scripting.FileSystemObject")
If objfso.FileExists(path) Then
  Set objFile = objFSO.OpenTextFile(path).ReadAll
End If

inputstr3 = inputbox("enter names of affected groups")`
grpString1 = split(inputstr3, ",")`

inputstr4 = inputbox("enter loss percentage")`
grpString2 = split(inputstr4, ",")`

ublptm = ubound(grpString1)
    for i=0 to ublptm 'where lptm = loss_pct_avg_monthyear[group] = percent;'
      lptmStr = lptmstr + "loss_pct_through_[" & grpString1(i) & "] = " & grpString2(i) & ";" & vbCrLf  
    next

re.Pattern = "(loss_pct_through_([a-zA-Z]{3,5}\d{4})\[([a-zA-Z_]{1,2}\d{1,2})\]\s=\s\d\.\d{14}[;]\n)\n(?=\}\n)"

objFile = re.Replace(objFile, vbCrLf & lptmstr & vbCrLf)

作为参考,.c 文件应该像这样更新:

原文件:

 loss_pct_through_nov2015[a4] = 0.13155605112872;
 loss_pct_through_nov2015[a5] = 0.23415898757080;

 loss_pct_through_dec2015[a2] = 0.00283148378304;
 loss_pct_through_dec2015[a3] = 0.39331380134641;
 loss_pct_through_dec2015[a4] = 0.56333929692615;
 loss_pct_through_dec2015[a5] = 0.04051541794440; <-append content from here
\n <-regex search for this newline character
}

更新文件:

 loss_pct_through_nov2015[a4] = 0.13155605112872;
 loss_pct_through_nov2015[a5] = 0.23415898757080;

 loss_pct_through_dec2015[a2] = 0.00283148378304;
 loss_pct_through_dec2015[a3] = 0.39331380134641;
 loss_pct_through_dec2015[a4] = 0.56333929692615;
 loss_pct_through_dec2015[a5] = 0.04051541794440;   
\n <--new newline character replacing the old one to append content below
 loss_pct_through_jan2016[a2] = 0.04051541794440;
 loss_pct_through_jan2016[a4] = 0.04051541794440;

}

一方面,这段代码:

If objfso.FileExists(path) Then
  Set objFile = objFSO.OpenTextFile(path).ReadAll
End If

应该给你一个错误,因为你正在从文件中读取一个字符串,但是尝试使用 Set 关键字将它分配给一个变量,这仅用于分配对象。

如果您没有收到错误,您的代码中很可能有一个 On Error Resume Next。删除那个。

将上面的代码更改为这样,以便您 a) 具有正确的赋值,并且 b) 不要使用误导性的变量名称:

If objfso.FileExists(path) Then
  txt = objFSO.OpenTextFile(path).ReadAll
End If

此外,我怀疑您的正则表达式与您认为的不匹配。您的输入文件似乎将换行符编码为 CR-LF,因为您将换行符添加为 vbCrLf。但是,在您的正则表达式中,您使用的是 \n,它只匹配 LF。将其更改为 \r\n(并删除无意义的组​​和断言):

re.Pattern = "(loss_pct_through_[a-zA-Z]{3,5}\d{4}\[[a-zA-Z_]{1,2}\d{1,2}\]\s=\s\d\.\d{14};\r\n\r\n)(\}\r\n)"

并像这样进行替换:

txt = re.Replace(txt, "" & lptmstr & vbCrLf & "")

以便在最后一行和右大括号之间插入新字符串。

并且不要忘记将修改后的字符串写回到文件中:

objFSO.OpenTextFile(path, 2).Write txt