使用VBScript在特定位置插入“ - ”

时间:2011-12-29 19:44:41

标签: vbscript insert

我有一个有多行的文件。

  • 每行第8个位置后需要“ - ”。
  • 我可以在第9个位置读取带“ - ”的行,但如果不存在,我就无法在第9个位置写“ - ”。

任何帮助都会非常感激。

4 个答案:

答案 0 :(得分:4)

您不能在VBScript字符串中插入字符,因为它们是不可变的;你必须连接Left(sOrgStr, 8) & "-" & Mid( sOrgStr, 9)的新字符串。 (数字为+ -1,具体取决于您的计算方式。)

答案 1 :(得分:3)

  • 打开文件C:\temp\log.txt
  • 使用单个regexo进行全局更改
  • 将新的更新文本写回原始文件

请更改您的文件路径以适合此行
StrFileName = "C:\temp\log.txt"

Const ForReading = 1    
Const ForWriting = 2
Dim objFSO
Dim objTF
Dim objRexex
Dim StrFileName
Dim strTxt

StrFileName = "C:\temp\log.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTF = objFSO.OpenTextFile(StrFileName, ForReading)
Set objregex = CreateObject("vbscript.regexp")
strTxt = objTF.ReadAll
objTF.Close
With objregex
    .Global = True
    .MultiLine = True
    .Pattern = "^(.{8})[^-](.*)$"
    strTxt = .Replace(strTxt, "$1" & "-" & "$2")
End With

Set objTF = objFSO.OpenTextFile(StrFileName, ForWriting)
objTF.Write strTxt
objTF.Close

答案 2 :(得分:2)

您可以使用此代码修复您阅读的字符串:

s="input string"
if (mid(s,9,1)<>"-") then 'the 9th character isn't "-"
    s=left(s,8) & "-" & mid(s,9)
end if

我建议您打开文件输入并将其重新写入另一个文本文件。

答案 3 :(得分:1)

您可以使用正则表达式。

如果你正在逐行阅读这些行,我认为你需要像

这样的东西
Set objRe = New RegExp
' this will match any line having 9 or more characters,
' where the 9-th character is not "-", and capture the first 8 characters in the group #1
objRe.Pattern = "^(.{8})[^-]"

' Open the file, read lines, in the inner loop, call:
line = objRe.Replace( line, "$1-" ) ' This will replace the RE with the group #1 followed by '-'
相关问题