简体   繁体   English

正则表达式匹配2个括号内的子字符串,例如[我想要这个文本]但是没有括号?

[英]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]"; 输出:“[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. 得到我想要的,但我想知道是否有一种方法可以在不执行String方法的情况下从Regex结果中省略delimeters [和]。

I would have thought there was a more elegant solution using Regex itself?? 我原本以为使用Regex本身有一个更优雅的解决方案?

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) 在“Aku”提出的解决方案中有一个重要的观点(我还没有代表发表评论)

You should note that the 2nd item in the Groups collection provides the value you need. 您应该注意,Groups集合中的第2项提供了您需要的值。 The first item (Groups(0)) is equivalent to the entire matched string (Match.ToString() or Match.Value) 第一项(Groups(0))相当于整个匹配的字符串(Match.ToString()或Match.Value)

Another way to do this, though I think it is a little slower than aku's example is this: 另一种方法,虽然我认为它比aku的例子慢一点是这样的:

        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. 我不知道,但我怀疑你可能会在列名之后,并且即将在你的结果字符串上执行.Split。 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
        */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM