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

How to make regular expression only accept special formula?

我正在使用 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:7,9

4-3+1+5

第一种情况,表示 sum(1,2,3,4,5,6,7,9),第二种情况表示 (4-3+1+5)。

但我不知道正则表达式如何处理它。 我搜索了 google,但没有找到我的案例的结果。

所以我需要 2 个正则表达式匹配项。

1,2,3:7,9

如果有这种模式,可以试试this one:

^\d+(?::\d+)?(?:,\d+(?::\d+)?)*$
  • ^\d+(?::\d+)?

matches string starts with a number(e.g. 1) or two numbers separated by a column (e.g. 1:2)

  • (?:,\d+(?::\d+)?)*$

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

如果有这种模式,可以试试this one:

^\d+(?:[+-]\d+)*$
  • 和上一个一样,这个简单多了

  • ^\d+

starts with a number(e.g. 12)

  • (?:[+-]\d+)*$

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)


此外,如果您至少需要一对数字。

例如 1,2 是允许的,但只是 1 是不允许的。您可以将 $ 之前的 * 更改为 +:

^\d+(?::\d+)?(?:,\d+(?::\d+)?)+$
^\d+(?:[+-]\d+)+$

如果您允许它们之间有空格:

^\d+(?:\s*:\s*\d+)?(?:\s*,\s*\d+(?:\s*:\s*\d+)?)+$
^\d+(?:\s*[+-]\s*\d+)+$