behnam
behnam

Reputation: 1143

Split math expression?

I wanna write calculation software,for separate numbers from operators i used Regex.Matches().but there is a bug that i displayed with used of image. In addition,math expression is :

5*10-18/(3+19)

    public class Tokenization
{
    public string MathExpression { get; set; }

    public Tokenization(string expression)
    {
        MathExpression = expression;
    }

    public List<string> MathExpressionParser()
    {
        int number;
        List<string> tokenList = new List<string>();
        List<string> tL = new List<string>();

        var numbersAndOperators = Regex.Matches(MathExpression, "(['*,+,/,-,),(']+)|([0-9]+)");

        foreach (var item in numbersAndOperators)
        {
            tokenList.Add(item.ToString());
            Debug.WriteLine(item.ToString());
        }

        return tokenList;
    }
}

}

enter image description here

Upvotes: 1

Views: 2036

Answers (3)

Bhushan Ingle
Bhushan Ingle

Reputation: 1

adding small improvement for decimal values.
update the reg-x with follow.

@"([*+/\-)(])|([0-9.]+|.)"

Upvotes: 0

nicael
nicael

Reputation: 18995

Remove +, since all the operators you match are single-char. Don't forget to escape -, it should be \-. Also there's no need in commas and quotes.

The result is:

([*+/\-)(])|([0-9]+)

Additionally, put @ before the regex string so as to avoid excess escaping. Or, escape the - with double \\:

([*+/\\-)(])|([0-9]+)

Upvotes: 2

Zein Makki
Zein Makki

Reputation: 30032

You can use this expression:

string expr = "5*10-18/(3+19)";

foreach(var match in Regex.Matches(expr, @"([*+/\-)(])|([0-9]+)"))
{
    Console.WriteLine(match.ToString());
}

Result:

5
*
10
-
18
/
(
3
+
19
)

Upvotes: 4

Related Questions