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

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)



Solution 1:[1]

It's overkill to use Regex.Replace for this. Use Trim instead.

string output = input.Trim(' ', '\t', '\n', '\v', '\f', '\r', '"');

And if you only want to remove whitespace that's outside the quotes, retaining any that's inside:

string output = input.Trim().Trim('"');

Solution 2:[2]

Besides using a regular expression you can just use String.Trim() - much easier to read, understand, and maintain.

var result = input.Trim('"', ' ', '\t');

Solution 3:[3]

Replace ^\s*"?|"?\s*$ with an empty string.

In C#, the regex would be:

string input = "  \"quoted string\"    "l
string pattern = @"^\s*""?|""?\s*$";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, "");
Console.WriteLine(result);

Solution 4:[4]

I would use String.Trim method instead, but if you want regex, use this one:

@"^(\s|")+|(\s|")+$"

Solution 5:[5]

I created a slightly modified version of another pattern that works pretty well for me. I hope this helps for separating normal command-line parameters and double-quoted sets of words that act as a single parameter.

String pattern = "(\"[^\"]*\"|[^\"\\s]+)(\\s+|$)";

Solution 6:[6]

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;
        }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3
Solution 4 Kamarey
Solution 5 Brandon Hawbaker
Solution 6 noseratio