覆盖异常

Exception to overwrite

我有一个 VBScript - 如果我 运行 我不希望它重复它正在替换的单词。我可以添加一个 If 语句来阻止它这样做吗?

Option Explicit
Const ForReading = 1
Const ForWriting = 2
Dim objFSO,objFile,strText,strNewText
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForReading)

strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, "<Jim","<!--<Jim")

'<pseudocode>
IF "<!--<Jim" = EXIST THEN DO NOTHING
END IF
'</pseudocode>

Set objFile = objFSO.OpenTextFile("C:\Users\newtons\Desktop\Text.txt",ForWriting)
objFile.WriteLine strNewText
objFile.Close
set objFSO = Nothing
set objFile = 

你可以用InStr()检查strText是否包含"Jim"或"James",并根据你真正想要实现的做或不做替换或保存.

Replace() 的文档解释了如何限制替换的数量 - 如果这是您的 "execption"/"repeating" 所暗示的。

演示:

>> WScript.Echo Replace("AA", "A", "a", 1, 1, vbTextCompare)
>>
aA
>>

<Jim 替换为 <!--Jim 而不是 <!--<Jim 以避免重复替换(即确保您的搜索字符串不是替换字符串的子字符串)。