Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for anything between []

Tags:

regex

asp.net

I need to find the regex for []

For eg, if the string is - Hi [Stack], Here is my [Tag] which i need to [Find].

It should return Stack, Tag, Find

like image 420
Ankit Avatar asked Sep 09 '10 13:09

Ankit


1 Answers

Pretty simple, you just need to (1) escape the brackets with backslashes, and (2) use (.*?) to capture the contents.

\[(.*?)\]

The parentheses are a capturing group, they capture their contents for later use. The question mark after .* makes the matching non-greedy. This means it will match the shortest match possible, rather than the longest one. The difference between greedy and non-greedy comes up when you have multiple matches in a line:

Hi [Stack], Here is my [Tag] which i need to [Find].
   ^______________________________________________^

A greedy match will find the longest string possible between two sets of square brackets. That's not right. A non-greedy match will find the shortest:

Hi [Stack], Here is my [Tag] which i need to [Find].
   ^_____^

Anyways, the code will end up looking like:

string regex = @"\[(.*?)\]";
string text  = "Hi [Stack], Here is my [Tag] which i need to [Find].";

foreach (Match match in Regex.Matches(text, regex))
{
    Console.WriteLine("Found {0}", match.Groups[1].Value);
}
like image 141
John Kugelman Avatar answered Sep 20 '22 21:09

John Kugelman