Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

Parsing a postfix expression in C#, my naive approach

, 21 Dec 2010
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Morten Nilsen

Norway Norway
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 21 Dec 2010
Article Copyright 2010 by Morten Nilsen
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid