我有以下字符串:
a,b,c,d.e(f,g,h,i(j,k)),l,m,n
会告诉我如何构建一个正则表达式,该正则表达式仅将括号的“第一级”返回给我,如下所示:
[0] = a,b,c, [1] = d.e(f,g,h,i.j(k,l)) [2] = m,n
目的是保留括号中具有相同索引的部分嵌套以操纵将来。
谢谢。
编辑
尝试改善示例…
想象一下我有这个字符串
username,TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2)),password
我的目标是将字符串转换为动态查询。然后,不以“ TB_”开头的字段我知道它们是主表的字段,否则我知道括号内的notifyandos字段与另一个表相关。但是我很难从“第一级”检索所有字段,因为我可以将它们与相关表分开,因此我可以递归地恢复其余字段。
最后,将会有如下内容:
[0] = username,password [1] = TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2))
希望我能解释得更好一些,对不起。
您可以使用此:
(?>\w+\.)?\w+\((?>\((?<DEPTH>)|\)(?<-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 \( (?<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)
您可以使用以下代码尝试:
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); }