简体   繁体   中英

Regex to match a substring within 2 brackets, e.g. [i want this text] BUT leave out the brackets?

I've managed to find the Regex to get almost the result I want here ie

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.

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"

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)

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
        */

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