我有以下字符串:
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_”开头的字段我知道它们是主表的字段,否则我知道括号内的信息字段与另一个表相关。 但是我很难检索所有字段“第一级”,因为我可以将它们从相关表中分离出来,我可以递归地恢复剩余的字段。
最后,会有类似的东西:
[0] = username,password
[1] = TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1, num_phone2))
我希望我已经解释得更好了,抱歉。
答案 0 :(得分:9)
您可以使用:
(?>\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);
}
答案 1 :(得分:0)
如果我理解你的例子,你正在寻找这样的东西:
(?<head>[a-zA-Z._]+\,)*(?<body>[a-zA-Z._]+[(].*[)])(?<tail>.*)
对于给定的字符串:
用户名,TB_PEOPLE.fields(FirstName,LastName,TB_PHONE.fields(num_phone1,num_phone2)),密码
此表达式将匹配
答案 2 :(得分:0)
我建议采用一种新的策略,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#本身并不能为您提供这种控制级别。