BlackBear
BlackBear

Reputation: 22979

Regex based numeric expression solver

I am making a simple numeric expression solver using regexes and right now I'm working at splitting polynomials into its terms. So this is what I got so far:

(.*?)([\+-](.*?))+

This doesn't work when negative numbers are involved. Take 3*-2+1 as an example: the terms I get are 3*, -2 and +1, which is obviously wrong.
I thought I could get away with a negative look behind before the sign so that signs preceded by * or / are discarded:

(.*?)((?<![\*/])[\+-](.*?))+

But this doesn't even work with positive numbers

Suggestions?

Upvotes: 2

Views: 236

Answers (1)

huysentruitw
huysentruitw

Reputation: 28131

Hope you didn't spend a lot of time creating your own parser ;)

I use this code to evaluate expressions:

class Program
{
    public static double Evaluate(string expression)  
    {  
        using (var stringReader = new StringReader("<dummy/>"))
        {
            var navigator = new XPathDocument(stringReader).CreateNavigator();
            expression = Regex.Replace(expression, @"([\+\-\*])", " ${1} "); // add some space
            expression = expression.Replace("/", " div ").Replace("%", " mod ");
            return (double)navigator.Evaluate(string.Format("number({0})", expression));
        }
    }

    static void Main(string[] args)
    {
        Console.WriteLine(Evaluate("3*-2+1"));
    }
}

Will output: -5

It is based on the XPathNavigator.Evaluate method. The Regex adds some spaces to the input and then division and modulo symbol are replaced.

Upvotes: 3

Related Questions