Advanced Command-Line Replace Command In VBScript

2019-09-06 08:56发布

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:

color 0a

input twelve = 0a "hi! that^'s great! "

execute :testfornum 'twelve'

exit

:testfornum

if numeric('1) (

return

) ELSE (

print 0a "oops 'twelve' should be numeric"

)

return

the apostrophe at line 2 should not be replaced, but the ones at line 3, 6 and 9 should be.

can anyone help me?

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

2条回答
乱世女痞
2楼-- · 2019-09-06 09:18

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

output:

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"
查看更多
我命由我不由天
3楼-- · 2019-09-06 09:23

You can't do this with a normal string replacement. A regular expression would work, though:

...
Set re = New RegExp
re.Pattern = "(^|[^^])'"
re.Global  = True

newContainment = re.Replace(lastContainment, "$1%")
...
查看更多
登录 后发表回答