首页 > 解决方案 > 如何使正则表达式只接受特殊公式?

问题描述

我正在使用 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)。

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

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

标签: javascripthtmlangularjsregex

解决方案


1,2,3:7,9

喜欢这种模式,你可以试试这个

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

匹配字符串以数字开头(例如1)或由一列分隔的两个数字(例如1:2

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

尽可能多地重复前面的模式并在其前面使用逗号,直到遇到字符串的结尾(例如,2:3,4:5,6


4-3+1+5

喜欢这种模式,你可以试试这个

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

  • ^\d+

以数字开头(例如12

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

尽可能多地重复前面带有 a-或前面的模式,直到遇到字符串的结尾(例如)++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+)+$

推荐阅读