我正在尝试编写一个正则表达式,允许用户输入正数和3位小数。我的正则表达式看起来像这样,然而,它并没有像我想的那样工作。
/\d*[1-9](\.\d{0,3})?/
这允许用户输入1.000
作为最小数字,但是,它不允许用户输入0.001
,这应该是输入输入的最小数量。
有谁知道正则表达式应该解决这个问题?
您的代码有另一个问题,它无法匹配10,因为您不允许那些地方为0。
你需要使用一些或陈述
const re = /(^([1-9]|\d{2,})(\.\d{0,3})?|0\.\d{0,2}[1-9])$/
const tests = ["0.001", "0.1", "0","0.0", "0.000","10.001", "10","11","1"]
tests.forEach(n => console.log(n, re.test(n)))
const re = /^(?!0+(?:\.0+)?$)\d+(?:\.\d+)?$/
const tests = ["0.001", "0.1", "0","0.0", "0.000","10.001", "10","11","1","1.22","1.222"]
tests.forEach(n => console.log(n, re.test(n)))
说明:
^ # beginning of string
(?! # negative lookahead, make sure we haven't after:
0+ # 1 or more zero
(?: # start non capture group
\. # a dot
0+ # 1 or more zero
)? # end group, optional
$ # end of string
) # end lookahead
\d+ # 1 or more digits
(?: # start non capture group
\. # a dot
\d+ # 1 or more digits
)? # end group, optionnal
$ # end of string
我个人只检查0并使正则表达式更简单,但这是一个解决方案,其中可以通过更改{1,3}来调整所需的小数位。
这个正则表达式的主旨是我们允许任何大于两位数的数字,然后只允许一个数字的1-9,然后可选地需要最多1个小数,后面是1-3个数字。
const r = /^((([0-9]{2,}){1}|[1-9]{1})(\.[0-9]{1,3}){0,1})$/;
const tests = ['1','2','0','1.001','1.001.1','999.001','9.01','9.0100','abc'];
tests.forEach(t=>console.log(t,r.test(t)));
另一种选择是使用否定前瞻从字符串的开头断言,右边的字符串既不是点也不是零,直到字符串结尾:
^(?![0.]+$)\d+(?:\.\d{1,3})?$
说明
^
字符串的开头(?![0.]+$)
用于断言右边的内容的否定前瞻不是字符类中重复1次以上直到字符串结尾的内容\d+
匹配1位数以上的数字(?:\.\d{1,3})?
可选的非捕获组,匹配点和1位数的倍数$
字符串的结尾const tests = ["0.001", "0.1", "0","0.0", "0.000","10.001", "10","11","1","1.22","1.222"]
tests.forEach(n => console.log(parseFloat(n) >= 0.001))
我真的认为这是在被推翻。
答案就在这里。
([1-9]\.[0-9][0-9][0-9]|[0]\.[1-9][0-9][0-9]|[0]\.[0][1-9][0-9]|[0]\.[0][0][1-9])
这应该匹配0.001~9.999