Parsing if-else if statement algorithm

后端 未结 3 862
渐次进展
渐次进展 2021-02-09 08:56

I am trying to create a very simple parser for an if-else type structure that will build and execute a SQL statement.

Rather than testing conditions for executing statem

3条回答
  •  醉话见心
    2021-02-09 09:50

    I recommend you use an existing code generator like ... C# or T4 templates or ASP.NET MVC partial views.

    But if you want to do this yourself you need some kind of recursion (or a stack which is equivalent). It could work like this:

    string BuildCode(string str)
    {
     foreach(Match ifMatch in Regex.Matches("#if(?[^\n\r]*)[\r\n]*(?.*?)#endif)
     {
      var condition = ifMatch.Groups["condition"].Value;
      return EvaluateCondition(condition) ? BuildCode(ifMatch.Value) : null;
     }
    }
    

    This is pseudo-code. You need to think through this yourself. This also does not support an else branch but you can add that easily.

    Here is a new answer: Use the CodeDom to compile a C# function. You can use the ful power of C# but have the C# code stored in a database or so. That way you don't have to redeploy.

提交回复
热议问题