Click here to Skip to main content
11,478,066 members (69,178 online)
Click here to Skip to main content

Tagged as

Parsing a postfix expression in C#, my naive approach

, 21 Dec 2010 CPOL 4.3K 1
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#! Pin
Morten Nilsen22-Dec-10 0:24
memberMorten Nilsen22-Dec-10 0:24 
Why are you talking about C++?
The code is C#!
GeneralIt should also be noted that the primary concept addressed i... Pin
TheRaven21-Dec-10 15:13
memberTheRaven21-Dec-10 15:13 
GeneralI have taken in account the fault mentioned in "Alternate 2"... Pin
Morten Nilsen21-Dec-10 1:40
memberMorten Nilsen21-Dec-10 1:40 
GeneralWell, I wasn't looking for performace. The Dictionary approa... Pin
CPallini22-Nov-10 8:50
mvpCPallini22-Nov-10 8:50 
GeneralI am also wondering if maybe it would be worth while to simp... Pin
Morten Nilsen22-Nov-10 5:16
memberMorten Nilsen22-Nov-10 5:16 
GeneralWell done. I thought about lambdas, but no luck here (no way... Pin
CPallini22-Nov-10 4:52
mvpCPallini22-Nov-10 4: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 | Terms of Use | Mobile
Web01 | 2.8.150520.1 | Last Updated 21 Dec 2010
Article Copyright 2010 by Morten Nilsen
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid