简体   繁体   中英

Double quote string replace in C#

How to replace the below string in C#

Current:

"John K "GEN" Greg"

The Goal:

 "John K \"GEN\" Greg"

This is wrong because I'm not escaping it properly:

s = s.Replace(""","\"");

What is syntax for replacing quotes with \\ (slash)?

Any help would be appreciated.

Thanks

s = s.Replace("\"", "\\\"");

or

s = s.Replace(@"""", @"\""");

In the first example the " has to be escaped with a backslash as it would otherwise end the string. Likewise, in the replacement string \\\\ is needed to yield a single backslash by escaping the escape character.

In the second example verbatim string literals are used, they are written as @"..." . In those literals no escape sequences are recognized, allowing you to write strings that contain lots of backslashes in a much cleaner way (such as regular expressions). The only escape sequence that works there is "" for a single " .

你应该使用双反斜杠:

s = s.Replace("\"", "\\\"");

To remove ALL quotes from a string, try:

field.Value = Regex.Replace(field.Value, @"[\\""]", "", RegexOptions.None);

What a pain trying to find this answer on the internet!

string MailFrom ="aaa@my.web.pk;\"PROMMS\" ccc@my.web.pk;";

string NewMailFrom = Regex.Replace(MailFrom, "\"[^\"]*\"", string.Empty);


Results

aaa@my.web.pk;ccc@my.web.pk;

s = s.Replace("\\"","\\\\\\"");

What are you escaping it for? If you're going to insert it into DB, consider using prepared statements instead. If you're going to use it in your HTML output, consider using some template engine that does it for yourself instead.

尝试: var result = yourString.Replace("\\"", "\\\\\\"");

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