C#中的双引号字符串替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9393879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:10:53  来源:igfitidea点击:

Double quote string replace in C#

c#

提问by pal

How to replace the below string in C#

如何在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

谢谢

采纳答案by Joey

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

在第二个示例中使用逐字字符串文字,它们被写为@"...". 在这些文字中,不识别转义序列,允许您以更简洁的方式(例如正则表达式)编写包含大量反斜杠的字符串。唯一适用的转义序列是""针对单个".

回答by zmbq

You should use a double backslash:

您应该使用双反斜杠:

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

回答by penartur

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

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

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

你逃避它干什么?如果要将其插入数据库,请考虑改用准备好的语句。如果您打算在 HTML 输出中使用它,请考虑使用一些为您自己做的模板引擎。

回答by Giorgio Minardi

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

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

回答by NotAProgrammer

To remove ALL quotes from a string, try:

要从字符串中删除所有引号,请尝试:

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

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

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

试图在互联网上找到这个答案真是太痛苦了!

回答by RameezAli

string MailFrom ="[email protected];\"PROMMS\" [email protected];";

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


Results

[email protected];[email protected];