Remove enclosing brackets from a string in c#

Arun picture Arun · Oct 11, 2012 · Viewed 33.1k times · Source

I need to remove enclosing brackets from a string in c# in code behind. For example, if I have a string as [My [] Groups], I want to turn it into My [] Groups.

Thanks.

Answer

Nasreddine picture Nasreddine · Oct 11, 2012

Try this:

yourString = yourString.Replace("[", string.Empty).Replace("]", string.Empty);

Updated answer since the question was edited:

string s = "[My [] Groups]";
string pattern = @"^(\[){1}(.*?)(\]){1}$";
Console.WriteLine(Regex.Replace(s, pattern, "$2")); // will print My [] Groups