tags:

views:

61

answers:

5

Let's assume I have the following text:

"something [234][3243]"

I am trying to pull the values in between the square brackets. I came up with the following regex expression: .*\[(.*)\].* however this only allows me to pull the last value in between the brackets, in this example 3243. How do I pull all values, meaning get more groups within my Match object.

A: 

You can try:

\[(.*?)]
tinifni
+2  A: 

If only numbers are allowed between the brackets, use

\[(\d+)\]

and use the .Matches method to get all matches.

var theString = "something [234][3243]";
var re = new Regex(@"\[(\d+)\]");
foreach (Match m in re.Matches(theString)) {
   Console.WriteLine(m.Groups[1].Value);
}

(if not only numbers are permitted, use \[([^]]+)\] instead.)

KennyTM
+3  A: 
        string s = "something[234][3243]";
        MatchCollection matches = Regex.Matches(s, @"(?<=\[)\d+(?=\])");
        foreach (Match m in matches)
        {
            Console.WriteLine(m.Value);
        }

You can do this with grouping parens, but if you use the look back and look ahead, then you will not need to pull the groups out of the match.

Seattle Leonard
+1  A: 

If you want to search for any string between square brackets and not only numbers, you could make the group pattern lazy (by adding ?) and do this:

\[(.+?)\]

Then iterate through all the matches to hit all bracket contents (contained in the capture group). As someone else said, if you add look-ahead and look-behind, the match itself will be sans brackets.

d7samurai
A: 

I know this wasn't a JavaScript question but here's how to do it in JS, since I don't know much C#. This doesn't use lookahead or lookbehinds and matches anything inside the brackets, not just numbers

var reg = /\[(\d+)\]/g;
var reg = /\[([^\]]+)\]/g;
var str = "something [234] [dog] [233[dfsfsd6]";

var matches = [];
var match = null;
while(match = reg.exec(str)) {
  // exec returns the first match as the second element in the array
  // and the next call to exec will return the next match or null
  // if there are no matches
  matches.push(match[1]);
}

// matches = [ "234", "dog", "233[dfsfsd6" ]
Juan Mendes