0

我尝试使用这个:Regex.Match(input, @"\(([^)]*)\)"),但这会给我“(StrB(StrC,StrD)”,这不是我想要的。

我想提取 2 个括号之间的字符串,但是里面的字符串可以有自己的一组括号,嵌套在主 2 个括号内,并且字符串可以用括号无限嵌套,例如:

"a(b(c(d(...))))",知道这是怎么做到的吗?谢谢。

4

2 回答 2

4

这将得到你想要的:

var regex = new Regex(
    @"(?<=\()(?:[^()]|(?<br>\()|(?<-br>\)))*(?(br)(?!))(?=\))");
var input = "StrA(StrB(StrC,StrD)(StrE)) StrF";
var matches = regex.Matches(input);

正则表达式分解如下:

(?<=\()         Preceeded by a (
(?:             Don't bother capturing a group
     [^()]+     Match one or more non-brackets
     |          OR
     (?<br>\()  Capture a (, increment the br count
     |          OR
     (?<-br>\)) Capture a ), decrement the br count or fail if it's 0
                (failing here will mean we've reached the end of our match)   
)
*               Zero or more times
(?(br)(?!))     Fail if there's the br count is greater than zero
                 (Literally, if it's greater than zero, match a (?!);
                 (?!) means 'not followed by ""', which always fails)
(?=\))          Succeeded by a )
于 2013-02-06T16:22:01.837 回答
0

作为另一种选择,您可以遍历一个字符串,并为括号使用计数器:对于“”增加 1,对于“ (”减少)。当计数器为零或到达字符串末尾时停止:

var str = "StrA(StrB(StrC,StrD)(StrE)) StrF";
string result = null;
int count = 0;
var firstIndex = str.IndexOf('(');
if (firstIndex != -1)
{
    count++;
    for (int i = firstIndex + 1; i < str.Length; i++)
    {
        switch (str[i])
        {
            case '(':
                count++;
                break;
            case ')':
                count--;
                break;
        }

        if (count == 0)
        {
            result = str.Substring(firstIndex + 1, i - firstIndex - 1);
            break;
        }
    }
}
于 2013-02-06T17:13:59.687 回答