Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Parsing a postfix expression in C#, my naive approach

Rate me:
Please Sign up or sign in to vote.
5.00/5 (5 votes)
21 Dec 2010CPOL 14.8K   1   6
Here is my take on the same, using Lambda expressions and slightly more advanced regular expression features:I have not tested this code, so errors may exist.This implementation will ignore unrecognized tokens. namespace Postfix { class Parser { static Dictionary<string,...
Here is my take on the same, using Lambda expressions and slightly more advanced regular expression features:

I have not tested this code, so errors may exist.
This implementation will ignore unrecognized tokens.

namespace Postfix
{
    class Parser
    {
        static Dictionary<string, Func<int, int, int>> operators;
        static Regex parserEngine = new Regex(@"\G(\s+(?<op>[-+*/])|\s*(?<value>-?[0-9]+))", RegexOptions.ExplicitCapture);

        static Parser()
        {
            operators = new Dictionary<string, Func<int, int, int>>();
            operators["+"] = (a, b) => a + b;
            operators["-"] = (a, b) => a - b;
            operators["*"] = (a, b) => a * b;
            operators["/"] = (a, b) => a / b;
        }

        static int parseExp(string s)
        {
            Stack<int> stack = new Stack<int>();

            foreach(Match match in parserEngine.Matches(s))
            {
                if(match.Success)
                {
                    foreach(KeyValuePair<string, string> m in match.Groups)
                    {
                        if(m.Key == "op")
                        {
                            if(stack.Count < 2)
                                throw new Exception("Invalid expression: out of stack.");
                            int b = stack.Pop();
                            int a = stack.Pop();
                            stack.Push(operators[m.Value](a, b));
                        }
                        else if(m.Key == "value")
                            stack.Push(int.Parse(m.Value));
                    }
                }
            }

            if(stack.Count != 1)
                throw new Exception("Invalid expression: not exactly one result on stack.");

            return stack.Pop();
        }

        static void Main()
        {
            string exp = "23 5 - 12 *";
            Console.WriteLine("expression '{0}' result is '{1}'", exp, Parser.parseExp(exp));
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Norway Norway
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralWhy are you talking about C++? The code is C#! Pin
Morten Nilsen21-Dec-10 23:24
Morten Nilsen21-Dec-10 23:24 
GeneralIt should also be noted that the primary concept addressed i... Pin
TheRaven21-Dec-10 14:13
TheRaven21-Dec-10 14:13 
GeneralI have taken in account the fault mentioned in "Alternate 2"... Pin
Morten Nilsen21-Dec-10 0:40
Morten Nilsen21-Dec-10 0:40 
GeneralWell, I wasn't looking for performace. The Dictionary approa... Pin
CPallini22-Nov-10 7:50
mveCPallini22-Nov-10 7:50 
GeneralI am also wondering if maybe it would be worth while to simp... Pin
Morten Nilsen22-Nov-10 4:16
Morten Nilsen22-Nov-10 4:16 
GeneralWell done. I thought about lambdas, but no luck here (no way... Pin
CPallini22-Nov-10 3:52
mveCPallini22-Nov-10 3:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.