gpt4 book ai didi

带小数点的基本数字的Javascript正则表达式?

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:41 27 4
gpt4 key购买 nike

我正在尝试使用正则表达式来验证十进制值。我在下面写了正则表达式,但它不允许第一位小数的值为 .5 或 .6 或 .1

正则表达式:/^\d[0-9]{0,13}(\.\d{1,2})?$/

规则:

  1. 它应该允许正数。
  2. 小数点前最多允许13个数字
  3. 它应该允许小数点后最多两位数。
  4. 它应该允许 .(点)和 .5
  5. 这样的数字
  6. 它不应该允许 .0

示例 - 有效输入

  • 0
  • 0.5
  • 1.55
  • .5
  • 1234567890123(小数点前13位)
  • 1234567890123.5
  • 1234567890123.00

示例 - 无效输入

  • .(点),
  • .0
  • 1.234
  • 5.
  • 12345678901234(小数点前14位)
  • 12345678901234.56

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));

最佳答案

我相信以下正则表达式应该满足您的所有条件:

^(\d{1,13}($|\.\d?\d$)|\.[1-9]\d?$)

第一种情况:1-13 位数字后跟空或“.”后跟一位或两位数

第二种情况:“.”后跟一个非零数字,最多一个其他数字

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));

关于带小数点的基本数字的Javascript正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49459946/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com