tags:

views:

743

answers:

3

I've managed to find the Regex to get almost the result I want here i.e.

Regex r1 = new Regex(@"\[(.*?)\]");
string row = HEADERNAMES[COL1,COL2,COL3,COL4];
Match match = r1.Match(row);
string result = match.ToString();

Outputs: "[COL1,COL2,COL3,COL4]";

I know I can then use:

result.Replace("[", "");
result.Replace("]", "");

to get exactly what I want but I was wondering if there was a way to ommit the delimeters [ and ] from the Regex result without performing the String methods.

I would have thought there was a more elegant solution using Regex itself??

Thanks in advance.

+10  A: 
Regex r1 = new Regex(@"\[(.+)\]");
string row = "HEADERNAMES[COL1, COL2, COL3, COL4]";
// Regex puts capture groups (i.e. things captured between ( and ) ) 
// in Groups collection
string match = r1.Match(row).Groups[1].Value;
//match = "COL1, COL2, COL3, COL4"
aku
You’d better use either the “?” quantor to make the “+” quantor not greedy or use “[^\]]+”.
Gumbo
You won't need the "?" you can only have one HEADERNAMES pattern in the string and the column name part can't have a "]" in it.
Martin Brown
+1  A: 

There's one major point to observe in the solution presented by "Aku" (I don't yet have the rep to comment)

You should note that the 2nd item in the Groups collection provides the value you need. The first item (Groups(0)) is equivalent to the entire matched string (Match.ToString() or Match.Value)

Cerebrus
A: 

Another way to do this, though I think it is a little slower than aku's example is this:

        Regex r1 = new Regex(@"(?<=\[).*(?=\])");
        string row = "HEADERNAMES[COL1, COL2, COL3, COL4]";
        Match match = r1.Match(row);
        Console.WriteLine(match.ToString());

        /* Output:
        COL1, COL2, COL3, COL4
        */

I don't know, but I suspect that you may be after the column names and are about to do a .Split on your result string. Did you know you could get all the column names individually using a single Regular Expression like this?

        Regex r1 = new Regex(@"\[(?:(?<colName>[^,\]]*)(?:,\s)?)*\]");
        string row = "HEADERNAMES[COL1, COL2, COL3, COL4]";
        Match match = r1.Match(row);

        foreach(Capture c in match.Groups["colName"].Captures)
            Console.WriteLine(c.ToString());

        /* Output:
        COL1
        COL2
        COL3
        COL4
        */
Martin Brown
I'd highly recommend using Split(), as the readability is MUCH better.
ScottS