正则表达式嵌套括号

Ver*_*ner 6 .net c# regex string

我有以下字符串:

a,b,c,d.e(f,g,h,i(j,k)),l,m,n
Run Code Online (Sandbox Code Playgroud)

会不会告诉我如何构建一个正则表达式,只返回括号的"第一级",如下所示:

[0] = a,b,c,
[1] = d.e(f,g,h,i.j(k,l))
[2] = m,n
Run Code Online (Sandbox Code Playgroud)

目标是保持括号中具有相同索引的部分嵌套以操纵未来.

谢谢.

编辑

试图改进这个例子......

想象一下,我有这个字符串

username,TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2)),password
Run Code Online (Sandbox Code Playgroud)

我的目标是将字符串转换为动态查询.那么不以"TB_"开头的字段我知道它们是主表的字段,否则我知道括号内的信息字段与另一个表相关.但是我很难检索所有字段"第一级",因为我可以将它们从相关表中分离出来,我可以递归地恢复剩余的字段.

最后,会有类似的东西:

[0] = username,password
[1] = TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2))
Run Code Online (Sandbox Code Playgroud)

我希望我已经解释得更好了,抱歉.

Cas*_*yte 10

你可以用这个:

(?>\w+\.)?\w+\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|[^()]+)*\)(?(DEPTH)(?!))|\w+
Run Code Online (Sandbox Code Playgroud)

通过您的示例,您获得:

0 => username
1 => TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2))
2 => password
Run Code Online (Sandbox Code Playgroud)

说明:

(?>\w+\.)? \w+ \(    # the opening parenthesis (with the function name)
(?>                  # open an atomic group
    \(  (?<DEPTH>)   # when an opening parenthesis is encountered,
                     #  then increment the stack named DEPTH
  |                  # OR
    \) (?<-DEPTH>)   # when a closing parenthesis is encountered,
                     #  then decrement the stack named DEPTH
  |                  # OR
    [^()]+           # content that is not parenthesis
)*                   # close the atomic group, repeat zero or more times
\)                   # the closing parenthesis
(?(DEPTH)(?!))       # conditional: if the stack named DEPTH is not empty
                     #  then fail (ie: parenthesis are not balanced)
Run Code Online (Sandbox Code Playgroud)

您可以使用以下代码进行尝试:

string input = "username,TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2)),password";
string pattern = @"(?>\w+\.)?\w+\((?>\((?<DEPTH>)|\)(?<-DEPTH>)|[^()]+)*\)(?(DEPTH)(?!))|\w+";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
    Console.WriteLine(match.Groups[0].Value);
}
Run Code Online (Sandbox Code Playgroud)