Javascript 如何使正则表达式只接受特殊公式?
我正在使用angularJS为特殊公式制作html页面Javascript 如何使正则表达式只接受特殊公式?,javascript,html,angularjs,regex,Javascript,Html,Angularjs,Regex,我正在使用angularJS为特殊公式制作html页面 <input ng-model="expression" type="text" ng-blur="checkFormula()" /> function checkFormula() { let regex; if (scope.formulaType === "sum") { regex = "need sum re
<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
}
}
或
第一种情况表示总和(1,2,3,4,5,6,7,9),第二种情况表示总和(4-3+1+5)
但我不知道正则表达式如何处理它。
我搜索了谷歌,但我没有得到我的案件的结果
所以我需要2个正则表达式匹配
1,2,3:7,9
对于此模式,您可以尝试:
^\d+(?:\d+)
1
)或以列分隔的两个数字(例如1:2
)
(?:,\d+(?::\d+)*$
,2:3,4:5,6
)
对于此模式,您可以尝试:
- 与前一个一样,这要简单得多
^\d+
12
)
(?:[+-]\d+*$
-
或+
,直到遇到字符串的结尾(例如+2-3+14
)
另外,如果您至少需要一对数字 例如
1,2
是允许的,但不允许1
。您只需将*
之前的$
更改为+
:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)+$
如果在它们之间允许空白:
^\d+(?:\s*:\s*\d+)?(?:\s*,\s*\d+(?:\s*:\s*\d+)?)+$
您想让1个正则表达式同时匹配它们还是让2个正则表达式分别匹配它们?需要两个正则表达式分别匹配它们。允许小数点/负数吗?还是只有正整数?只有正数。
^\d+(?::\d+)?(?:,\d+(?::\d+)?)*$
4-3+1+5
^\d+(?:[+-]\d+)*$
^\d+(?::\d+)?(?:,\d+(?::\d+)?)+$
^\d+(?:[+-]\d+)+$
^\d+(?:\s*:\s*\d+)?(?:\s*,\s*\d+(?:\s*:\s*\d+)?)+$
^\d+(?:\s*[+-]\s*\d+)+$