简体   繁体   中英

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 \\ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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