我有以下字符串:
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
目标是将具有相同索引的部分保留在嵌套的括号中以操纵 future 。
谢谢。
编辑
正在尝试改进示例...
假设我有这个字符串
username,TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2)),password
我的目标是将字符串转换为动态查询。 那么不以“TB_”开头的字段我知道它们是主表的字段,否则我知道括号内的informandos字段与另一个表相关。 但是我很难检索“第一级”所有字段,因为我可以将它们与相关表分开,我可以递归地恢复剩余字段。
最后,会是这样的:
[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);
}
关于c# - 正则表达式嵌套括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19596502/