C# 将部分字符串替换为中的特殊字符

C# 将部分字符串替换为中的特殊字符,c#,C#,我想将:reference1\”:“null\”替换为reference1\”:null 要编辑的字符串的示例部分: {\"reference1\":\"null\",\"secondarything\": 我试过文字: strValue = strValue.Replace(@reference1\":\" null\","reference1\": null"); 我在

我想将:
reference1\”:“null\”
替换为
reference1\”:null

要编辑的字符串的示例部分:

{\"reference1\":\"null\",\"secondarything\":
我试过文字:

strValue = strValue.Replace(@reference1\":\" null\","reference1\": null");

我在别处有引文要保留。正是引号和反斜杠的组合让我感到困惑。

您需要使用
\
-

strValue = strValue.Replace("reference1\":\"null\"" , "reference1\": null");
编辑1: 如果您的字符串已包含
\
,则使用其他
\
对其进行转义,因此现在代码如下所示-

strValue = strValue.Replace("reference1\\\":\\\"null\\\"", "reference1\\\": null");

您需要使用
\
-

strValue = strValue.Replace("reference1\":\"null\"" , "reference1\": null");
编辑1: 如果您的字符串已包含
\
,则使用其他
\
对其进行转义,因此现在代码如下所示-

strValue = strValue.Replace("reference1\\\":\\\"null\\\"", "reference1\\\": null");

使用普通字符串,并在每个
\
之前添加反斜杠:

strValue.Replace("reference1\\\":\\\" null\\\"", "reference1\\\": null")
或者使用逐字字符串,并将

strValue.Replace(@"reference1\"":\"" null\""", @"reference1\"": null")


这就是说,这看起来像是一个XY问题:这个字符串看起来非常像JSON,而试图对JSON进行字符串操作通常是个坏主意。使用json.net之类的json解析器可能是解决您试图解决的任何问题的更好途径。

使用普通字符串,并在每个
\
之前添加反斜杠:

strValue.Replace("reference1\\\":\\\" null\\\"", "reference1\\\": null")
或者使用逐字字符串,并将

strValue.Replace(@"reference1\"":\"" null\""", @"reference1\"": null")


这就是说,这看起来像是一个XY问题:这个字符串看起来非常像JSON,而试图对JSON进行字符串操作通常是个坏主意。使用json.net之类的json解析器可能是解决您试图解决的任何问题的更好途径。

事实上,在格式化您的帖子后,很明显在第一次编辑中隐藏了反斜杠。这看起来像json,如果是,则有错误,并且有更好的方法来解决这一问题。这是一些json,这是一些测试数据,用于查找错误/可能不正确的反馈。不完美,但上述情况意味着我没有发现问题。谢谢,实际上,格式化了你的帖子后,很明显在第一次编辑中隐藏了反斜杠。这看起来像是json,如果是的话,有些地方出了问题,有更好的方法可以做到这一点。这是一些json,这是一些测试数据来发现错误/可能是错误的反馈。不完美,但上述情况意味着我没有发现问题。谢谢