parseSimpleOperation function
Parses a simple mathematical operation expression and returns a
TSimpleOperation
object that represents the operation.
The expression
parameter is a string that represents the mathematical
operation in the format of "operand operator operand = result", where
operand
is a number (positive or negative), operator
is a mathematical
operator (+
, -
, *
, /
, ×
, or ÷
), and result
is an optional
number that represents the result of the operation.
This function only supports simple operations with two operands and one
operator. If the input expression
is not in the expected format, or if
the operands or operator are not valid, the function returns null
.
Returns a TSimpleOperation
object that represents the operation.
Implementation
TSimpleOperation? parseSimpleOperation(String expression) {
// Define a regular expression called `pattern` that matches the format of
// "operand operator operand = result".
final pattern = RegExp(
r'^\s*(-?\d+(?:\.\d+)?)\s*([+\-*/×÷])\s*(-?\d+(?:\.\d+)?)(?:\s*=\s*(-?\d+(?:\.\d+)?))?\s*$');
// Use the `firstMatch` method of the `RegExp` class to extract the operands,
// operator, and result from the `expression` string.
final match = pattern.firstMatch(expression);
if (match == null) {
// Return null if the expression doesn't match the expected format.
return null;
}
// Extract the operands, operator, and result from the `Match` object.
final operand1 = match.group(1);
final operator = match.group(2);
final operand2 = match.group(3);
final result = match.group(4);
if (operand1 == null || operator == null || operand2 == null) {
// Return null if any of the operands or operator is null.
return null;
}
return TSimpleOperation(
operands: [operand1, operand2],
operator: operator,
result: result,
);
}