Javascript 如何使正则表达式只接受特殊公式?

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

我正在使用angularJS为特殊公式制作html页面

<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+)+$