^ : begining of string
(?: : start non capture group
\d{1,4} : 1 up to 4 digit
| : OR
(?= : lookahead
.{1,5}$ : 1 up to 5 character (it could be .{3,5} if at least 1 digit is mandatory on each side of the dot)
) : end lookahead
\d+ : 1 or more digits, integer part
\. : dot
\d{1,2} : 1 or 2 digits, decimal part
) : end group
$ : end of string
var test = [
123,
1234,
12.34,
123.4,
12345,
12.345,
1.234
];
console.log(test.map(function (a) {
return a+' :'+/^(?:\d{1,4}|(?=.{1,5}$)\d+\.\d{1,2})$/.test(a);
}));
4 回答
使用前瞻来断言最多有1个点:
(?!([^.]\.){2})
意思是“向前看,没有2个点(?!\d{5})
表示"looking ahead, there aren't 5 straight digits"[\d.]{3,5}
表示"3-5 of digits and dots"见live demo .
要将十进制数字限制为最大值2,请添加
(?!.*\.\\d{3,}$)
,这是"dot then 3+ digits at the end"的负面预测,即:见live demo .
它不漂亮,但你可以这样做:
只要确保你周围有一些边界控制字符 .
这样说:
您可以see here它按预期工作 .
但是,我会建议在这个具体案例中使用另一种工具 .
以下正则表达式应该这样做......
见 regex demo / explanation
如果你的正则表达式接受它,你可以使用如下前瞻:
编辑:允许最多2位小数
Explanation: