正则表达式嵌套括号

我有以下字符串:

a,b,c,de(f,g,h,i(j,k)),l,m,n 

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

 [0] = a,b,c, [1] = de(f,g,h,ij(k,l)) [2] = m,n 

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

谢谢。

编辑

试图改进这个例子……

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

 username,TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2)),password 

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

最后,会有类似的东西:

 [0] = username,password [1] = TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2)) 

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

你可以用这个:

 (?>\w+\.)?\w+\((?>\((?)|\)(?<-DEPTH>)|[^()]+)*\)(?(DEPTH)(?!))|\w+ 

通过您的示例,您获得:

 0 => username 1 => TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2)) 2 => password 

说明:

 (?>\w+\.)? \w+ \( # the opening parenthesis (with the function name) (?> # open an atomic group \( (?) # 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) 

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

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

我建议一个新的策略,R2 – 用算法做。 虽然你可以建立一个最终接近你所要求的正则表达式,但是当你找到新的边缘情况时,它将非常难以维护。 我不会说C#,但这个伪代码可以让你走上正轨:

 function parenthetical_depth(some_string): open = count '(' in some_string close = count ')' in some_string return open - close function smart_split(some_string): bits = split some_string on ',' new_bits = empty list bit = empty string while bits has next: bit = fetch next from bits while parenthetical_depth(bit) != 0: bit = bit + ',' + fetch next from bits place bit into new_bits return new_bits 

这是理解它的最简单的方法,算法目前是O(n^2) – 内部循环的优化使其成为O(n) (除了字符串复制,这是最糟糕的部分这个):

 depth = parenthetical_depth(bit) while depth != 0: nbit = fetch next from bits depth = depth + parenthetical_depth(nbit) bit = bit + ',' + nbit 

通过巧妙地使用缓冲区和缓冲区大小,以空间效率为代价,可以提高字符串复制效率,但我不认为C#本身可以为您提供这种控制级别。

如果我理解你的例子,你正在寻找这样的东西:

 (?[a-zA-Z._]+\,)*(?[a-zA-Z._]+[(].*[)])(?.*) 

给定字符串:

username,TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1,num_phone2)),密码

这个表达式会匹配

  • 用户名,用于组长
  • TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1,num_phone2))用于组
  • 尾的 密码