tags:

views:

116

answers:

4

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)

+1  A: 

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);
Amarghosh
`@"^\s*\"?|\"?\s*$"` is not possible in C#. In verbatim strings use `""` instead of `\"` for quotes. Also you don't need to create a new instance of Regex, just use Regex.Replace.
Yuriy Faktorovich
@Yuriy Thanks, updated.
Amarghosh
+1  A: 

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

@"^(\s|")+|(\s|")+$"
Kamarey
+12  A: 

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

string output = input.Trim(' ', '\t', '\n', '\v', '\f', '\r', '"');
LukeH
+3  A: 

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

var result = input.Trim('"', ' ', '\t');
Daniel Brückner