[英]How to make regular expression only accept special formula?
I'm making html page for special formula using angularJS.我正在使用 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
}
}
So I want to make inputbox only accept my formula.所以我想让输入框只接受我的公式。 Formulas are two cases.
公式是两种情况。
1,2,3:7,9
or或者
4-3+1+5
First case, means sum(1,2,3,4,5,6,7,9) and second case means (4-3+1+5).第一种情况表示 sum(1,2,3,4,5,6,7,9),第二种情况表示 (4-3+1+5)。
But I don't know regular expression how to process it.但我不知道正则表达式如何处理它。 I searched google, but I didn't get result for my case.
我搜索了谷歌,但我没有得到我的案例的结果。
So I want to need 2 regex match.所以我想需要2个正则表达式匹配。
1,2,3:7,9
Fot this pattern, you can try this one :喜欢这种模式,你可以试试这个:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)*$
^\d+(?::\d+)?
matches string starts with a number(eg
1
) or two numbers separated by a column (eg1:2
)匹配字符串以数字开头(例如
1
)或由一列分隔的两个数字(例如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 (eg
,2:3,4:5,6
)尽可能多地重复前面带有逗号的前一个模式,直到遇到字符串的结尾(例如
,2:3,4:5,6
)
4-3+1+5
Fot this pattern, you can try this one :喜欢这种模式,你可以试试这个:
^\d+(?:[+-]\d+)*$
Like the previous one, this is much simpler和上一个一样,这要简单得多
^\d+
starts with a number(eg
12
)以数字开头(例如
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 (eg+2-3+14
)尽可能多地重复前面带有
-
或+
的模式,直到遇到字符串的结尾(例如+2-3+14
)
Also, if you need at least one pair of numbers.此外,如果您需要至少一对数字。
Such as 1,2
is allowed but just 1
is not.例如
1,2
是允许的,但只有1
是不允许的。 You can just change the *
before $
to +
:您可以将
$
之前的*
更改为+
:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)+$
^\d+(?:[+-]\d+)+$
And if you allow white spaces in between them:如果你允许它们之间有空格:
^\d+(?:\s*:\s*\d+)?(?:\s*,\s*\d+(?:\s*:\s*\d+)?)+$
^\d+(?:\s*[+-]\s*\d+)+$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.