js中怎么使用正则表达式如何匹配数值,范围,小数点后两位

需要满足以下几个条件

  1. 匹配的一定为数字类型的
  2. 匹配数值的范围在-1000 ~ 1000
  3. 数值后面需要两位小数
  4. 可以输入0

示例:

11          OK
01          不OK
10.111      不OK
1001        不OK
1000.01     不OK
1000.00     OK
-11         OK
-01         不OK
0           OK
11.        不OK
11.0       OK

寻求答案,谢谢各位啦

阅读 3.5k
3 个回答

var reg = /^\-?([1-9]\d{0,2}|1000|0)(\.00)?$/;
console.log(reg.test('11'),'OK');
console.log(reg.test('01'),'不OK');
console.log(reg.test('10.111'),'不OK');
console.log(reg.test('1001'),'不OK');
console.log(reg.test('1000.01'),'不OK');
console.log(reg.test('1000.00'),'OK');
console.log(reg.test('-11'),'OK');
console.log(reg.test('-01'),'不OK');
console.log(reg.test('0'),'OK');
console.log(reg.test('11 .'),'不OK');

数值后面需要两位小数
11 OK ???????

可以输入0
01 不OK ???????

11 . 不OK ??????
[11 .]难道不能正则识别为11吗?

最后推测一下:
你是想匹配[-1000, 1000]的小数点最多为2位的所有非0开头数字吗?
我语文真jb垃圾,看不懂你的意思

回复一楼大神: 如果11.0也可以呢
回复二楼大神: 是你那个意思,最后那个小数点不小心打过去了

推荐问题