简体   繁体   English

VB.Net/C#-自定义函数上的拆分字符串

[英]VB.Net/C# - Split string on custom function

I'm working on a custom mathematical expression calculator, but I'm having problems at parsing nested conditional expression like this one: 我正在开发一个自定义数学表达式计算器,但是在解析嵌套条件表达式时遇到了这样的问题:

IIF("M"="M",(IIF(100 < 50,(IIF(2 > 0.45,2,1)),(IIF(2 > 0.45,4,3)))),(IIF(100 < 46,(IIF(2 > 0.45,2,1)),(IIF(2 >0.45,4,3)))))

What I'd like to do is to split the IIF function by commas in order to get its parameters: 我想做的是用逗号分割IIF函数以获得其参数:

Dim condition = "M"="M"
Dim truePart = (IIF(100 < 50,(IIF([2 > 0.45,2,1)),(IIF(2 >0.45,4,3))))
Dim falsePart = (IIF(100 < 46,(IIF(2 > 0.45,2,1)),(IIF(2 >0.45,4,3)))))

At the moment I'm using Regex to parse single IIF function by getting what is inside the parentheses and the split it by commas: 目前,我正在使用Regex来解析单个IIF函数,方法是获取括号内的内容并将其用逗号分隔:

\((.*?)\)

Obviously that doesn't work with such expression since it will stop at the first closing parentheses, therefore I thought about using this to get all the other characters: 显然,这不适用于此类表达式,因为它将在第一个右括号处停止,因此我考虑过使用该表达式来获取所有其他字符:

\((.*?)\).*

But now I'm not sure how to split it, since using commas is not an option anymore. 但是现在我不确定如何分割它,因为不再使用逗号。

The answer from theory is that regular expressions are not capable to do what you requested because they "cannot count". 从理论上得出的答案是,正则表达式无法执行您要求的操作,因为它们“无法计数”。 However, you need to count. 但是,您需要计数。

The practise says that .NET regular expressions are no regular expressions but stack machines. 实践表明,.NET正则表达式不是正则表达式,而是堆栈机。 With a group (?<Group>.*) you in fact add an entry to a stack of that group. 实际上,使用组(?<Group>.*)您可以将条目添加到该组的堆栈中。 With (?<-Group>) , you can remove an entry from that stack. 使用(?<-Group>) ,可以从该堆栈中删除一个条目。 You can also test whether the stack is empty. 您还可以测试堆栈是否为空。

Out of curiosity, I gave it a try and I believe that 出于好奇,我尝试了一下,我相信

[\\(,]([^\\(\\)]|(?<Par>\\()|(?<-Par>\\)))*(?(Par)---|[,\\)])

should work, where --- is used as an escape sequence. 应该可以工作,其中---用作转义序列。 If you understand that "regular expression" right away, then I think you are good to go. 如果您立即了解“正则表达式”,那么我认为您很好。 In all other cases, I would rather recommend you to write a parser manually. 在所有其他情况下,我建议您手动编写一个解析器。 Otherwise, you are not going to understand your code 5min after you have tested it. 否则,测试代码后5分钟,您将不会理解代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM