Advanced Command-Line Replace Command In VBScript

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-16 18:15:37

问题


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

回答1:


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"



回答2:


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%")
...


来源:https://stackoverflow.com/questions/25221565/advanced-command-line-replace-command-in-vbscript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!