我正在尝试使用正则表达式来验证小数值。我在下面写了正则表达式,但它不允许第一个十进制值为 .5或.6或.1
常规展示:/^\d[0-9]{0,13}(\.\d{1,2})?$/
规则:
示例 - 有效输入
示例 - 输入无效
const valid = [
"0",
"0.5",
"1.55",
".5",
"1234567890123",
"1234567890123.5",
"1234567890123.00",
];
const invalid = [
".",
".0",
"1.234",
"5.",
"12345678901234",
"12345678901234.56",
];
const rgx = /^\d[0-9]{0,13}(\.\d{1,2})?$/
console.log("Checking valid strings (should all be true):");
valid.forEach(str => console.log(rgx.test(str), str));
console.log("\nChecking invalid strings (should all be false):");
invalid.forEach(str => console.log(rgx.test(str), str));
答案 0 :(得分:4)
我认为以下正则表达式应符合您的所有标准:
^(\d{1,13}($|\.\d?\d$)|\.[1-9]\d?$)
第一种情况:1-13位数字后面没有任何内容或者是"。"后跟一两位数
第二种情况:a"。"接着是非零数字,最多是一个其他数字
const valid = [
"0",
"0.5",
"1.55",
".5",
"1234567890123",
"1234567890123.5",
"1234567890123.00",
];
const invalid = [
".",
".0",
"1.234",
"5.",
"12345678901234",
"12345678901234.56",
];
const rgx = /^(\d{1,13}($|\.\d?\d$)|\.[1-9]\d?$)/
console.log("Checking valid strings (should all be true):");
valid.forEach(str => console.log(rgx.test(str), str));
console.log("\nChecking invalid strings (should all be false):");
invalid.forEach(str => console.log(rgx.test(str), str));

答案 1 :(得分:1)
我认为这应该满足您的大部分要求,但不是全部,限制为小数点后9位
( /^(\d+\.?\d{0,9}|\.\d{1,9})$/ )
并且这个没有小数限制
( /^(\d+\.?\d*|\.\d+)$/ )
答案 2 :(得分:1)
其他答案不允许.0x的情况,我认为这是有效的吗?我认为你需要分别测试xxx [.xx]和.xx。
^(\d{1,13}(\.\d{1,2})?|\.(0[1-9]|[1-9]\d?))$
答案 3 :(得分:1)
要匹配您的值,您可以使用non capturing group alternation使用|
并指定要匹配的内容。
^(?:\.[1-9][0-9]?|\d{1,13}(?:\.\d{1,2})?|.\d{2})$
这也会匹配.01
而非.0
<强>解释强>
^
字符串的开头(?:
非捕获组
\.[1-9][0-9]?
匹配点后跟0,然后是0-9 |
或\d{1,13}
匹配1 - 13位数字(?:
非捕获组
\.\d{1,2}
匹配一个点和1或2位数字)?
关闭非捕获组并将其设为可选|
或.\d{2}
匹配点后跟2位数字)
关闭非捕获组$
字符串结尾
const valid = [
"0",
".01",
"0.5",
"1.55",
".5",
"1234567890123",
"1234567890123.5",
"1234567890123.00",
];
const invalid = [
".",
".0",
"1.234",
"5.",
"12345678901234",
"12345678901234.56",
];
const rgx = /^(?:\.[1-9][0-9]?|\d{1,13}(?:\.\d{1,2})?|.\d{2})$/;
console.log("Checking valid strings (should all be true):");
valid.forEach(str => console.log(rgx.test(str), str));
console.log("\nChecking invalid strings (should all be false):");
invalid.forEach(str => console.log(rgx.test(str), str));
&#13;
要与.01
不匹配,您可以使用:
^(?:\d{1,13}(?:\.\d{1,2})?|\.[1-9][0-9]?)$
const valid = [
"0",
"0.5",
"1.55",
".5",
"1234567890123",
"1234567890123.5",
"1234567890123.00",
];
const invalid = [
".",
".0",
".01",
"1.234",
"5.",
"12345678901234",
"12345678901234.56",
];
const rgx = /^(?:\d{1,13}(?:\.\d{1,2})?|\.[1-9][0-9]?)$/;
console.log("Checking valid strings (should all be true):");
valid.forEach(str => console.log(rgx.test(str), str));
console.log("\nChecking invalid strings (should all be false):");
invalid.forEach(str => console.log(rgx.test(str), str));
&#13;