tags:

views:

93

answers:

3

Hi,

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

+7  A: 

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);
}
John Kugelman
How do i get the words from the text in asp.net ?? I want to retrieve all the words in the []
Thx .. it worked
+1 for beautiful explanation
LeChe
+1  A: 
\[([\w]+?)\]

should work. You might have to change the matching group if you need to include special chars as well.

Femaref
+3  A: 

Depending on what environment you mean:

\[([^\]]+)]
Michel de Ruiter
Ah, .NET... This was an Emacs regex. :-)
Michel de Ruiter
I think you missed a `]` even in Emacs syntax.
KennyTM
I took the liberty to change it into a .NET compatible one. Note that the `]` only needs escaping inside the character set, not outside of it (although it doesn't hurt to escape it...).
Bart Kiers
@KennyTM: you're right!
Michel de Ruiter