我正在尝试验证以逗号分隔的数字 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/