简体   繁体   中英

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

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!

You are almost there. You have to use the Replace method:

var pattern = @" \[(.*?)\]";
var query = "University of Hawaii [Maui/Oahu/Kaui]";
Console.WriteLine(Regex.Replace(query, pattern, string.Empty));

Using only \\[.*?\\] you can match everything including the brackets.

As I am not very familiar with C#, could you then replace it with an empty string?

You can do it like this:

var pattern = @"\s\[.*\]";
var regex = new Regex(pattern);
var result = regex.Replace(query, "");

What about this:

var pattern = @"\[.*\]";
var query = "University of Hawaii [Maui/Oahu/Kaui]";
var result = Regex.Replace(query, pattern);
Console.WriteLine(result);

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM