C# Use Regex to Remove everything inside brackets and the brackets themselves

Viewed 3040

I have a string:

var schoolName = "University of Hawaii [Maui/Oahu/Kaui]";

I would like to remove everything inside the brackets and the brackets themselves so the string outputs "University of Hawaii" only.

I have been looking for the correct regex but haven't found the solution for doing this:

var pattern = @"\[(.*?)\]";
var query = "University of Hawaii [Maui/Oahu/Kaui]";
var matches = Regex.Matches(query, pattern);

foreach (Match m in matches) {
    Console.WriteLine(m.Groups[1]);
}

Thanks for your help!

5 Answers

here is the code I am using to do the job :

var pattern = @"\[(.*?)\]";
var result = Regex.Replace(stringToSanitize, pattern, string.Empty);
Related