将if语句转换为条件语句

时间:2012-04-23 01:20:59

标签: c# regex replace

我正在尝试转换IF语句,如下所示

SET RESULT = IF(C>(X-2), (A+B), C) //IF C< X-2 return A+B otherwise return C

到下面的条件语句

SET RESULT = C>(X-2)?(A+B):C

我编写了一个代码,用于扫描整个字符串以及IF(,的出现情况。当有多个IF语句(如下面的

)时,我的算法无效
SET RESULT = IF(C>(X-2), IF(P>C,2,3),C)

这是代码......

        string data = "SET RESULT=IF(C>(X-2), (A+B), C)";
        string output = string.Empty;

        int indexofIF = data.IndexOf("IF");
        int obCount = 0;
        int cbCount = 0;
        if (indexofIF > -1)
        {
            string script = data.Substring(indexOfIF, (data.Length-indexOfIF-1))
            for(int index=0; index<script.Length; index++)
            {
                int obIndex = data.IndexOf('(', index);
                if(obIndex>-1)
                    obCount++;
                int cbIndex = data.IndexOf(')', index);
                if(cbIndex>-1)
                    cbCount++;

                if(obCount==cbCount)//Found the end of If statement
                {
                    string tempData = data.Substring(0, index);
                    int count = tempData.Count(f => f == ',');//Get the number of occurences of ','
                    if (count == 2)//There are only 2 commas
                    {
                        int firstIndex = tempData.IndexOf(',');
                        int lastIndex = tempData.LastIndexOf(',');
                        string condtion = tempData.Substring(3, (firstIndex - 4));
                        string trueCond = tempData.Substring(firstIndex + 1, (lastIndex - firstIndex - 1));
                        string falseCond = tempData.Substring(lastIndex + 1, (index - lastIndex - 1));
                        output = condtion + "?" + trueCond + ":" + falseCond;

                    }
                    else //More than 2 commas
                    {

                    }
                }

            }

        }

我不确定这是否适用于复杂的情况。有没有更好的其他方式这样做?也许使用regex或任何其他字符串替换操作..

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上。

我会:

  • 将每个字符读入一个小缓冲区
  • 评估缓冲区以查找单词“IF”
  • 设置一个标志,以便您知道自己处于IF语句中
  • 清除缓冲区
  • 评估括号
  • 跟踪括号的打开/关闭
  • 执行任何其他逻辑(例如逗号解析)
  • 继续直到字符串结尾
  

也许使用正则表达式或任何其他字符串替换操作..

(IF.*?(?=IF|$))分解多个IF语句,但它不处理额外的解析,并要求输入数据遵循严格的结构。跟踪括号是棘手/不可能的(请参阅对此答案的评论),并且更容易由状态机处理。

就个人而言,我喜欢逐字符解析的控制/灵活性。像Code Mirror这样的工具使用这种方法来解析源代码。

一旦成功提取了字符串的一部分(例如,将A + B > C之类的公式解构为其部分),您可能会发现正则表达式很有用。

相关问题