То, что вы пытаетесь сделать, часто называют «зачисткой» или «расстановкой цитат». Обычно, когда значение равно в кавычках , это означает не только то, что оно окружено символами кавычек (например, в данном случае "), но также то, что оно может содержать или не содержать специальные символы для включения кавычка сама внутри цитируемого текста.
Короче, вы должны рассмотреть что-то вроде:
string s = @"""Hey ""Mikey""!";
s = s.Trim('"').Replace(@"""""", @"""");
Или при использовании знака апострофа:
string s = @"'Hey ''Mikey''!";
s = s.Trim('\'').Replace("''", @"'");
Кроме того, иногда значения, которые вообще не нуждаются в кавычках (то есть не содержат пробелов), в любом случае могут не нуждаться в кавычках. Вот почему проверка символов кавычек перед усечением является разумной.
Рассмотрите возможность создания вспомогательной функции, которая будет выполнять эту работу предпочтительным образом, как в примере ниже.
public static string StripQuotes(string text, char quote, string unescape)a
{
string with = quote.ToString();
if (quote != '\0')
{
// check if text contains quote character at all
if (text.Length >= 2 && text.StartsWith(with) && text.EndsWith(with))
{
text = text.Trim(quote);
}
}
if (!string.IsNullOrEmpty(unescape))
{
text = text.Replace(unescape, with);
}
return text;
}
using System;
public class Program
{
public static void Main()
{
string text = @"""Hello World!""";
Console.WriteLine(text);
// That will do the job
// Output: Hello World!
string strippedText = text.Trim('"');
Console.WriteLine(strippedText);
string escapedText = @"""My name is \""Bond\"".""";
Console.WriteLine(escapedText);
// That will *NOT* do the job to good
// Output: My name is \"Bond\".
string strippedEscapedText = escapedText.Trim('"');
Console.WriteLine(strippedEscapedText);
// Allow to use \" inside quoted text
// Output: My name is "Bond".
string strippedEscapedText2 = escapedText.Trim('"').Replace(@"\""", @"""");
Console.WriteLine(strippedEscapedText2);
// Create a function that will check texts for having or not
// having citation marks and unescapes text if needed.
string t1 = @"""My name is \""Bond\"".""";
// Output: "My name is \"Bond\"."
Console.WriteLine(t1);
// Output: My name is "Bond".
Console.WriteLine(StripQuotes(t1, '"', @"\"""));
string t2 = @"""My name is """"Bond"""".""";
// Output: "My name is ""Bond""."
Console.WriteLine(t2);
// Output: My name is "Bond".
Console.WriteLine(StripQuotes(t2, '"', @""""""));
}
}
https://dotnetfiddle.net/TMLWHO