C# Regular Expression: Remove leading and trailing double quotes (")

Viewed 24054

If I have a string like below... what is the regular expression to remove the (optional) leading and trailing double quotes? For extra credit, can it also remove any optional white space outside of the quotes:

string input = "\"quoted string\""   -> quoted string
string inputWithWhiteSpace = "  \"quoted string\"    "  => quoted string

(for C# using Regex.Replace)

6 Answers

My 2c, as I couldn't find what I was looking for. This verion removes the first pair of quotes and spaces on each side of them.

        public static string RemoveQuotes(string text)
        {
            var regex = new Regex(@"^\s*\""\s*(.*?)\s*\""\s*$");
            var match = regex.Match(text);
            if (match.Success && match.Groups.Count == 2)
            {
                return match.Groups[1].Value;
            }
            return text;
        }
Related