我对 vb 脚本有一个非常基本的疑问:
Msgbox "This is myName" ' This works fine
Msgbox "This is "myName"" ' This gives an error
Msgbox "This is ""myName""" 'This works fine
我的问题是,如果我需要保存(在变量中)或显示带双引号的字符串,为什么我需要对单词或短语使用双引号两次。使用常见的双引号是否并不意味着我想显示整个内容或者可以将其保存为变量中的字符串?
在 VBScript 中,字符串文字用双引号 (
"
) 括起来。这就是您的第一个示例所显示的内容:
Msgbox "This is myName" ' This works fine
但是,如果您想在字符串文字中包含双引号字符inside,则会遇到问题,因为 VBScript 会将其找到的第二个双引号字符解释为表示字符串文字的结尾。这就是你的第二个例子所显示的:
Msgbox "This is "myName"" ' This gives an error
^ ' because it prematurely terminates the string here
' and doesn't know what to do with the trailing "
幸运的是,有一个逃生舱口。它涉及使用另一个字符来转义双引号字符,表明 VBScript 应该将其作为文字双引号字符处理,而不是神奇的“字符串文字结尾”字符。恰巧 VBScript 使用的转义字符是双引号字符。这就是你的第二个例子所显示的:
Msgbox "This is ""myName""" 'This works fine
\
) 作为转义字符。这可能会让事情变得更容易看到。假设 VBScript 使用反斜杠而不是双引号作为转义字符,您的代码将如下所示:
Msgbox "This is \"myName\"" ' doesn't work in VBScript; example only
如果这种语法让您感到困扰,您可以为双引号声明一个常量并每次都使用它:
Const Quote = """"
' ... later in the code ...
Msgbox "This is " & Quote & "myName" & Quote
。不管偶然与否,在 VB/VBS 中它是双引号。不管偶然与否,我们只能在文字字符串中嵌入双引号。我们不能嵌入其他特殊字符,例如 Tab。 但是,使用 VB/VBS 转义字符可以简化我们的编码。
str = """D:\path\to\xyz.exe"" ""arg 1"" ""arg 2"""
WScript.Echo str ' "D:\path\to\xyz.exe" "arg 1" "arg 2"
str = Chr(34) & "D:\path\to\xyz.exe" & Chr(34) & " " _
& Chr(34) & "arg 1" & Chr(34) & " " & Chr(34) & "arg 2" & Chr(34)
WScript.Echo str ' "D:\path\to\xyz.exe" "arg 1" "arg 2"
str = Join(Array("", "D:\path\to\xyz.exe", " ", "arg 1", " ", "arg 2", ""), Chr(34))
WScript.Echo str ' "D:\path\to\xyz.exe" "arg 1" "arg 2"
但我个人更喜欢使用
Replace
,因为它使我的代码更具可读性。
str = Replace("'D:\path\to\xyz.exe' 'arg 1' 'arg 2'", Chr(39), Chr(34))
WScript.Echo str ' "D:\path\to\xyz.exe" "arg 1" "arg 2"
您可以使用
Replace
(如果方便的话)和其余特殊字符。
str = Replace(Replace("A|B|C!1|2|3", "!", vbNewLine), "|", vbTab)
WScript.Echo str
'A B C
'1 2 3
要在字符串文字中包含分隔符,必须对其进行转义(标记为不表示字符串的“结束”或“开始”。“在字符串文字中的转义标记是“”。在 VBscript 中给出“” - 。 其他语言使用
\"
转义双引号。
那么
Msgbox "This is ""myName""" 'This works fine
x = "This is ""myName"""
如果您要显示(或存储)内容,那么这是正确的 VBScript
This is "myName"
。
命令可以工作,而你的 2nd 却不能。