RegEx to remove single quote, parentheses or square bracket from both beginning and end of a string [closed]

You don’t need regular expressions for this. string.Trim is the best implementation of the “number of ‘,() or [] can be any and all should be removed” requirement and test #5.

var cleaned = dirty.Trim("'()[]".ToCharArray());

With some tests:

const string expected = "My name";

Func<string, string> clean = given => given.Trim("'()[]".ToCharArray());

Assert.AreEqual(expected, clean("'My name'"));
Assert.AreEqual(expected, clean("[My name]"));
Assert.AreEqual(expected, clean("(My name)"));
Assert.AreEqual(expected, clean("'([My name])'"));
Assert.AreEqual(expected, clean("('My name]'"));
Assert.AreEqual(expected, clean("''([[[(My name)]]])''"));
Assert.AreEqual("My n'am]e", clean("My n'am]e"));

Leave a Comment