javascript - 如何使正则表达式只接受特殊公式?
问题描述
我正在使用 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个正则表达式匹配。
解决方案
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+)+$
推荐阅读
- azure - 无法使用静态公共 IP 创建 AKS 负载平衡
- c# - 使用存储在 s3 中的凭据初始化 firebase
- batch-file - 有没有办法让 CMD 运行 24 小时?
- javascript - 使用 jquery 和 cookie 增加/减少字体大小
- python - ValueError:logits 和标签必须具有相同的形状 ((1, 21) vs (21, 1))
- java - 为什么JVM不直接对局部变量数组进行赋值操作?
- java - Spark 3.0.1 是否支持窗口函数上的自定义聚合器?
- c++ - 通过/非默认在类构造函数中传递 std::filesystem::path
- java - 长流过滤
- ubuntu - Ansible - rsyslog 安装和配置