c# - 正则表达式嵌套括号

标签 c# .net regex string

我有以下字符串:

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/

相关文章:

c# - 实现这种延迟加载的设计模式?

.net - 使用[JsonConverter]属性时,我的JsonConverter类中的StackOverflowException

PHP正则表达式字符串中最多允许1个 '.'或 '_'字符,并且 '.'或 '_'不能位于字符串的开头或结尾

python - Python 中的正则表达式?

c# - 如何将现有程序集转换为 ms 单元测试程序集?

javascript - 通过正则表达式匹配计算 MongoDB 中的记录

javascript - 浏览器不在启用 CORS 的情况下跨域发送 cookie

c# - 为什么在LINQ查询中调用方法时不能使用范围值的属性作为参数?

c# - 如何在 HttpWebRequest POST 中将对象作为参数传递?

c# - 在 C# 中,我如何以编程方式知道操作系统是 x64 还是 x86