我需要验证页面范围的正则表达式。(例如。列印自订页)
目前,我已经尝试过这个表达式。
/^(?!([ \d]*-){2})\d+(?: *[-,] *\d+)*$/
它应该接受如下的值
1, 3, 6-9
1-5, 5
6, 9
它不应该接受这样的值
,5
5-,9
9-5,
2,6-
10-1
发布于 2019-11-08 10:32:53
在这一点上,我不会费心于一个新手难以阅读的正则表达式。使用纯js的无正则表达式但冗长的解决方案:
演示:
const isNumeric = input => !isNaN(input) // you may also check if the value is a nonzero positive integer
const isOrdered = (start, end) => parseInt(start) < parseInt(end)
const isRangeValid = range => range.length == 2 && range.every(isNumeric) && isOrdered(range[0], range[1])
const isSingleValid = single => single.length == 1 && isNumeric(single[0])
function f(input) {
const inputs = input.split(',').map(x => x.trim());
for (const x of inputs) {
if (!x) return false;
const pages = x.split('-');
if (!isSingleValid(pages) && !isRangeValid(pages))
return false;
}
return true;
}
console.log(f("1, 3, 6-9"))
console.log(f("1-5, 5"))
console.log(f("6, 9"))
console.log(f(",5"))
console.log(f("5-,9"))
console.log(f("9-5,"))
console.log(f("2,6-"))
console.log(f("10-1"))
console.log(f("56-0"))
https://stackoverflow.com/questions/58764552
复制相似问题