1,2,3:7,9
Fot this pattern, you can try this one:
^d+(?::d+)?(?:,d+(?::d+)?)*$
matches string starts with a number(e.g. 1
) or two numbers separated by a column (e.g. 1:2
)
repeats the previous pattern with a comma in front of it as many time as possible until meets the end of the string (e.g. ,2:3,4:5,6
)
4-3+1+5
Fot this pattern, you can try this one:
^d+(?:[+-]d+)*$
starts with a number(e.g. 12
)
repeats the previous pattern with a -
or +
in front of it as many time as possible until meets the end of the string (e.g. +2-3+14
)
Also, if you need at least one pair of numbers.
Such as 1,2
is allowed but just 1
is not. You can just change the *
before $
to +
:
^d+(?::d+)?(?:,d+(?::d+)?)+$
^d+(?:[+-]d+)+$
And if you allow white spaces in between them:
^d+(?:s*:s*d+)?(?:s*,s*d+(?:s*:s*d+)?)+$
^d+(?:s*[+-]s*d+)+$
I’m making html page for special formula using angularJS.
<input ng-model="expression" type="text" ng-blur="checkFormula()" />
function checkFormula() {
let regex;
if (scope.formulaType === "sum") {
regex = "need sum regular expression here"; // input only like as 1, 2, 5:6, 8,9
} else {
regex = "need arithmetic regular expression here"; // input only like as 3 + 4 + 6 - 9
}
if (!regex.test(scope.expression)) {
// show notification error
Notification.error("Please input expression correctly");
return;
}
// success case
if (scope.formulaType === "sum") {
let fields = expression.split(',');
let result = fields.reduce((acc, cur) => { return acc + Number(cur) }, 0);
// processing result
} else {
// need to get fields with + and - sign.
// TODO: need coding more...
let result = 0;
// processing result
}
}
So I want to make inputbox only accept my formula.
Formulas are two cases.
1,2,3:7,9
or
4-3+1+5
First case, means sum(1,2,3,4,5,6,7,9) and second case means (4-3+1+5).
But I don’t know regular expression how to process it.
I searched google, but I didn’t get result for my case.
So I want to need 2 regex match.
needs two regex to match them separately.
Only positive numbers.