VBScript中的高级命令行替换命令 [英] Advanced Command-Line Replace Command In VBScript
问题描述
我正在为自己的计算机语言编写一个编译器。现在,在编译语言之前,我实际上需要通过命令行vbs程序用百分数(%)替换所有的撇号(’)。但是,仅当前面没有回音符号(^)时,才需要替换撇号。因此,例如,在这段代码中:
I'm writing a compiler for my won computer language. Now before the language can be compiled i actually need to replace all apostrophes (') with percents (%) via a command-line vbs program. But the apostrophes only need to be replaced if there is NOT a circumflex accent (^) in front of it. So for example, in this code:
颜色0a
color 0a
输入十二= 0a嗨!那^太好了!
input twelve = 0a "hi! that^'s great! "
执行:testfornum'twelve'
execute :testfornum 'twelve'
退出
:testfornum
:testfornum
如果numeric('1)(
if numeric('1) (
return
)ELSE(
print 0a哎呀,'十二'应该是数字
print 0a "oops 'twelve' should be numeric"
)
返回
不应替换第2行的撇号,而应该替换第3、6和9行的撇号。
the apostrophe at line 2 should not be replaced, but the ones at line 3, 6 and 9 should be.
有人可以帮助我吗?
这是我到目前为止的内容:
this is what i have so far:
'syntax: (cscript) replace.vbs [filename] "StringToFind" "stringToReplace"
Option Explicit
Dim FileScriptingObject, file, strReplace, strReplacement, fileD, lastContainment, newContainment
file=Wscript.arguments(0)
strReplace=WScript.arguments(1)
strReplacement=WScript.arguments(2)
Set FileScriptingObject=CreateObject("Scripting.FileSystemObject")
if FileScriptingObject.FileExists(file) = false then
wscript.echo "File not found!"
wscript.Quit
end if
set fileD=fileScriptingobject.OpenTextFile(file,1)
lastContainment=fileD.ReadAll
newContainment=replace(lastContainment,strReplace,strReplacement,1,-1,0)
set fileD=fileScriptingobject.OpenTextFile(file,2)
fileD.Write newContainment
fileD.Close
推荐答案
由于@Ansgar的解法对于前导'(非^之前),这是一种在测试脚本中使用替换函数的方法,可以简化进一步的实验:
As @Ansgar's solution fails for the special case of a leading ' (no non-^ before that), here is an approach that uses a replace function in a test script that makes further experiments easy:
Option Explicit
Function fpR(m, g1, g2, p, s)
If "" = g1 Then
fpR = "%"
Else
fpR = m
End If
End Function
Function qq(s)
qq = """" & s & """"
End Function
Dim rE : Set rE = New RegExp
rE.Global = True
rE.Pattern = "(\^)?(')"
Dim rA : Set rA = New RegExp
rA.Global = True
rA.Pattern = "([^^])'"
'rA.Pattern = "([^^])?'"
Dim s
For Each s In Split(" 'a^'b' a'b'^'c nix a^''b")
WScript.Echo qq(s), "==>", qq(rE.Replace(s, GetRef("fpR"))), "==>", qq(rA.Replace(s, "$1%"))
Next
输出:
cscript 25221565.vbs
"" ==> "" ==> ""
"'a^'b'" ==> "%a^'b%" ==> "'a^'b%" <=== oops
"a'b'^'c" ==> "a%b%^'c" ==> "a%b%^'c"
"nix" ==> "nix" ==> "nix"
"a^''b" ==> "a^'%b" ==> "a^'%b"
这篇关于VBScript中的高级命令行替换命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!