我正在尝试转义字符串中的 \
和 "
,像这样:
text.Replace("\\", "\\\\").Replace("\"", "\\\"");
但是对于
text
的结果,arash "moeen"
原来是这样
arash \\\"moeen\\\"
我该如何解决这个问题?
我正在尝试转义字符串中的 \
和 "
,像这样:
text.Replace("\\", "\\\\").Replace("\"", "\\\"");
text
的结果,arash "moeen"
arash \\\"moeen\\\"
@
来表示字面字符串。text.Replace(@"this", @"that");
例子:
text.Replace(@"\", @"\\").Replace(@"""", @"\""");
a "b"
,请键入 @"a ""b"""
。 - Nameless Onevar text = @"arash ""moeen""";
如果我理解正确,首先,text = arash "moeen"
不是有效的正则字符串字面量。我猜你的字符串是这样的;
string s = "text = arash \"moeen\"";
这将被打印为
text = arash "moeen" // I think this is your original string.
由于你的字符串中包含了 arash \"moeen\"
,因此你只需要将其中的 "
替换为 \"
,如下:
string s = "text = arash \"moeen\"";
s = s.Replace("\"", "\\\"");
所以你的结果将会是arash \"moeen\"
更多信息:转义序列
如果这是一个JSON字符串,那么我的回答将无效 :-p
string text = @"arash ""moeen""";
MessageBox.Show(text.Replace(@"\", @"\\").Replace(@"""", @"\"""));
string test = "He said to me, \"Hello World\". How are you?";
在这两种情况下,字符串都没有改变 - 它中间有一个被转义的双引号。 这只是一种告诉C#该字符属于字符串而不是字符串终止符的方式。
当你想要从 arash "moeen"
中获取 arash \"moeen\"
时,使用 text.Replace(", \");
。
arash \"moeen\"
? - Marlon