javascript - 验证数字范围

标签 javascript regex

我正在尝试验证以逗号分隔的数字 1-384 唯一列表(不重复)。

  • 1、2、3、5、6、7、9 有效
  • 1-3、5-7、9 有效
  • 2、2、6 无效
  • 2、无效
  • 1、2、3、4、15、6、7、385 无效,因为最后一个数字大于 384

我尝试了以下 RegEx 模式,但还不够:

/^(?!.*(\b(?:[1-9]|[1-2]\d|3[0-1])\b).*\b\1\b)(?:[1-9]|[1-2]\d|3[0-1])(?:,(?:[1-9]|[1-2]\d|3[0-1]))*$/

最佳答案

滤镜和套装可能更护眼

“1-385”也是假的吗?

const isValid = str => {
  str = str.replace(/\s+/g, "")
  const rng = str.split(",").filter(item => {
    if (item === null || item === "") return false
    if (isNaN(item)) {
      const [from, to] = item.split('-')
      return +from > 0 && +from < 385 && 
             +to   > 0 &&   +to < 385
    }
    item = +item
    return item > 0 && item < 385;
  });
  return [...new Set(rng)].join(",") === str;
};


const arr = ["1, 2, 3, 5, 6, 7, 9",
  "1-3, 5-7, 9",
  "1-385",
  "1-384",
  "2, 2, 6",
  "2,",
  "1, 2, 3, 4, 15, 6, 7, 384",
  "1, 2, 3, 4, 15, 6, 7, 385",
  "0, 2, 3"
]


const res = arr.map(str => ({ [str]: isValid(str) }));
console.log(res)

关于javascript - 验证数字范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65614163/

相关文章:

javascript - 无法获取文本值

javascript - 需要一个 javascript 或 jquery 库来将 xpath 转换为 jquery 中可选择的 CSS3 格式

javascript - IE 10 不遵守 z-index

javascript - 如何按整数查找数字?

javascript - 在 JavaScript 中读取文件而不上传它们

mysql - 如何从查询中的url中提取id?

android - Sqlite Android 中如何实现分界?

javascript - 将 RegExp 转换回字符串

c++ - 使用 regex.h 进行全词匹配

带有特殊字符的 Python 正则表达式