Parsing a postfix expression in C#, my naive approach

来源:互联网 发布:找人做淘宝网页 编辑:程序博客网 时间:2024/04/29 14:15
using System;using System.Text.RegularExpressions;using System.Collections.Generic; namespace Postfix{class Parser{public delegate int BinOp(int a, int b);static int add(int a, int b) { return a + b;}static int sub(int a, int b) { return a - b; }static int mul(int a, int b) { return a * b; }static int div(int a, int b) { return a / b; } static int parseExp(string s){Dictionary<string, BinOp> oper = new Dictionary<string, BinOp>();List<int> stack =new List<int>(); oper["+"] = add;oper["-"] = sub;oper["*"] = mul;oper["/"] = div; Regex rxnum = new Regex(@"/G/s*-?([0-9]+)/s+");Regex rxop = new Regex(@"/G(/+|/-|/*|//)");int start = 0;do{Match m = rxnum.Match(s, start);if (m.Success){stack.Add(Int32.Parse(m.ToString()));}else{m = rxop.Match(s, start);if (m.Success){int c = stack.Count;if (c < 2) throw new Exception("Invalid expression: out of stack.");stack[c - 2] = oper[m.ToString()](stack[c - 2], stack[c - 1]);stack.RemoveAt(c - 1);}else break;}start = start + m.Length;} while (true); if (stack.Count != 1) throw new Exception("Invalid expression: more than one result on stack.");if (start != s.Length) throw new Exception("Invalid expression: unrecognized token."); return stack[0];} static void Main(){string exp = "23 5 - 12 *";Console.WriteLine("expression '{0}' result is '{1}'", exp,  Parser.parseExp(exp));}}}

 

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));
}
}
}