简体   繁体   English

为什么这个字符串不能正确逃逸?

[英]Why won't this string escape properly?

我有一个如下所示的字符串,尽管它在到达冒号时会引发错误,但我使用@来转义所有内容:

string vmListCommand = @"vim-cmd vmsvc/getallvms | sed '1d' | awk '{if ($1 > 0) print $1":"$2}'";

Remove @ and escape double quotes using \\ : 删除@并使用\\转义双引号:

string vmListCommand = "vim-cmd vmsvc/getallvms | sed '1d' | awk '{if ($1 > 0) print $1\":\"$2}'";

You wrote: 你写了:

I have used @ to escape everything 我已经用@逃避了一切

@ is used to change escaping bahaviour, not to escape everything . @用于更改逃避的行为,而不是逃避一切 If a string is prefixed with @ then escape sequences ( \\ ) are ignored. 如果字符串以@开头,则转义序列( \\ )将被忽略。

Use \\ for escape in your string. 在字符串中使用\\进行转义。

Example: 例:

string str1 ="hello\\";

您需要删除文字并转义

string vmListCommand = "vim-cmd vmsvc/getallvms | sed '1d' | awk '{if ($1 > 0) print $1\":\"$2}'";

There is one character that needs to be escaped in literal strings. 有一个字符需要按原义字符串进行转义。 The double quote " . If you don't escape it, how would the compiler know which " are part of the string, and which terminate the string? 双引号"如果你不逃避它,如何将编译器知道"是字符串的一部分,并终止字符串?

To escape a " in a literal string, simply double it: 要在文字字符串中转义" ,只需将其加倍即可:

 @"vim-cmd vmsvc/getallvms | sed '1d' | awk '{if ($1 > 0) print $1"":""$2}'"

Alternatively you could switch to the normal string syntax, and escape with \\ . 或者,您可以切换到常规字符串语法,并使用\\转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM