Data Browser - Viewing Site  Sector 23 Code Bank Logged in as:  Guest  




           


Support multi-character operators in the Mathos Parser
The Mathos Expression Parser by default supports " <", "> " and "=" but not " <=", "!=", "and", "or", or other logical operands with 2 or 3 characters.
( http://support.mathosproject.com/questions/are-multi-character-operators-supported/ )

By extending to support 2-3 characters, the following assertions become possible:

Assert.AreEqual(1M, parser.Parse("1 <= 2 AND (2 <= 1 OR 1 != 2 OR 2 <> 3)"));

(Supports greater than or equal, less than or equal, not equal, and "and" or "or" (in any case))

To fix:
Replace the following code in Scanner method:

Replace

else

{

tokens.Add(ch.ToString());

}

With

else if ((i + 2) < expr.Length && _operatorList.Contains(expr.Substring(i, 3).ToUpper()))
{ // a 3-character operand
tokens.Add(expr.Substring(i, 3).ToUpper());
i += 2;
}
else if ((i + 1) < expr.Length && _operatorList.Contains(expr.Substring(i, 2).ToUpper()))
{ // a 2-character operand
tokens.Add(expr.Substring(i, 2).ToUpper());
i++;
}
else

{

tokens.Add(ch.ToString());

}


and then add your operators to the constructor:

OperatorList.Add("/"); // division 2
OperatorList.Add("*"); // multiplication
OperatorList.Add("-"); // subtraction
OperatorList.Add("+"); // addition

OperatorList.Add("> ="); // greater than or equal
OperatorList.Add(" <="); // less than or equal
OperatorList.Add(" <> "); // not equal
OperatorList.Add("!="); // not equal

OperatorList.Add("> "); // greater than
OperatorList.Add(" <"); // less than
OperatorList.Add("="); // are equal
OperatorList.Add("AND"); // AND
OperatorList.Add("OR"); // OR



_operatorAction.Add("/", (numberA, numberB) => numberA / numberB);
_operatorAction.Add("*", (numberA, numberB) => numberA * numberB);
_operatorAction.Add("+", (numberA, numberB) => numberA + numberB);
_operatorAction.Add("-", (numberA, numberB) => numberA - numberB);

_operatorAction.Add("> =", (numberA, numberB) => numberA > = numberB ? 1 : 0);
_operatorAction.Add(" <=", (numberA, numberB) => numberA <= numberB ? 1 : 0);
_operatorAction.Add(" <> ", (numberA, numberB) => numberA != numberB ? 1 : 0);
_operatorAction.Add("!=", (numberA, numberB) => numberA != numberB ? 1 : 0);

_operatorAction.Add("> ", (numberA, numberB) => numberA > numberB ? 1 : 0);
_operatorAction.Add(" <", (numberA, numberB) => numberA < numberB ? 1 : 0);
_operatorAction.Add("=", (numberA, numberB) => numberA == numberB ? 1 : 0);
_operatorAction.Add("AND", (numberA, numberB) => (numberA != 0 && numberB != 0) ? 1 : 0);
_operatorAction.Add("OR", (numberA, numberB) => (numberA != 0 || numberB != 0) ? 1 : 0);

Created By: amos 2/23/2015 5:58:01 PM
Updated: 2/24/2015 6:21:51 PM