我正在尝试编写一个正则表达式来验证十进制数字。该数字必须包含小数点。小数点右边必须有一个数字[0-9]。小数点左边最多可以有5位数字,但除非以0开头,否则它们不能以0开头。允许的:0.1(如果后跟小数位,则第一位数只能为零)10345.0(小数点左边最多5位,小数点右边必须有1位)不允许:0(无小数位)10(无小数位)(小数点右边没有数字)。(小数点两侧没有数字).1(小数点左边没有数字)此正则表达式验证小数点前的内容^(?:[1-9][0-9]{0,4}|0)$此正则表达式验证小数点后的内容^[0-9]{1}+$我只是不知道如何将两者结合起来,使得小数位是强制性的。我该如何解决这个问题?
3 回答

凤凰求蛊
TA贡献1825条经验 获得超4个赞
据我所知,这行得通
^(?:[1-9]\d{0,4}|0)\.\d$
展开式
^ # BOS
(?:
[1-9] \d{0,4} # 1-5 digits, must not start with 0
| # or,
0 # 0
)
\. \d # decimal point and 1 digit
$ # EOS

眼眸繁星
TA贡献1873条经验 获得超9个赞
那应该工作
const r = /^(?:[1-9]\d{0,4}|0)\.\d+/
const arr = ['0', '1', '1.2', '1.', '1.123', '0123.1', '123.123', '1234.1', '12345.12345678', '123456.123', '0.12'];
arr.forEach((val) => {
console.log(val, r.test(val));
})
添加回答
举报
0/150
提交
取消