不要在字符串中转义双引号

时间:2015-01-09 17:05:57

标签: java string escaping double-quotes

我编写了一个命令行脚本,我正在使用java对其进行测试。

在命令行中,我这样写:script -html="anchor bold"所以在使用java代码测试时,我的字符串究竟应该如何勾勒出来?

-html=anchor bold"它不起作为双引号不包含所以我的测试失败

-html=\"anchor bold\"这可以逃脱双引号,但我想要它。

-html=\\\"anchor bold\\\"这导致-html=\"anchor bold\",但我不想要任何斜杠。

我使用String[]数组来执行命令。

new String[] { "--path=" + p,
               "--user=" + user,
               "--html=\"anchor bold\"",
               "--port=8081"
            }

命令行参数是:

path/executeScript --path=path1 --user=testUser --html="anchor bold" --port=8081

4 个答案:

答案 0 :(得分:11)

如果你想用Java测试你的脚本,参数包含引号,你没有任何选择,你将不得不逃避它。

String[] command  = new String[] {
    "path/executeScript",
    "--path=" + p,
    "--user=" + user,
    "--html=\"anchor bold\"",
    "--port=8081"
}
Runtime.getRuntime().exec(command);

技术说明:https://stackoverflow.com/a/3034195/2003986

答案 1 :(得分:4)

要声明字符串文字,唯一的方法是在字符串中使用双引号括起字符。像这样:

"String Characters"
... String Characters

来自Java Language Specifications §3.10.5

  

字符串文字由用双引号括起来的零个或多个字符组成。字符可以用转义序列(§3.10.6)表示 - 一个转义序列用于U + 0000到U + FFFF范围内的字符,两个转义序列用于UF 010000范围内UTF-16代理字符代码单元到U + 10FFFF。

StringLiteral:
  " {StringCharacter} "
StringCharacter:
  InputCharacter but not " or \ 
  EscapeSequence
   有关EscapeSequence的定义,请参阅§3.10.6

[...]

的   以下是字符串文字的示例:

""                    // the empty string
"\""                  // a string containing " alone
"This is a string"    // a string containing 16 characters
"This is a " +        // actually a string-valued constant expression,
    "two-line string"    // formed from two string literals

因为转义双引号是编译时语法要求,所以必须转义字符串文字中的双引号。

您可以尝试使用 Unicode literal ,但我非常怀疑(剧透:它没有)编译器会接受它:

"--html=\u0022anchor bold\u0022" — Wrong

使用转义:

"--html=\"anchor bold\"" — Right

编译器将其视为:

... --html="anchor bold"

另见:

答案 2 :(得分:2)

在你想要用作文字字符的任何东西前面使用转义字符,然后照常将双引号放在它周围。

script -html="\"anchor bold\""

答案 3 :(得分:0)

我能想到的一种方式..使用角色。

"--html=" + '"' + "anchor bold" + '"'
相关问题