验证打印正则表达式的页面范围



我需要验证页面范围的正则表达式。(例如打印自定义页面(

目前,我已经尝试过这个表达

/^(?!([ d]*-){2})d+(?: *[-,] *d+)*$/

它应该接受这样的值

1, 3, 6-9
1-5, 5
6, 9

它不应该接受像这样的值

,5
5-,9
9-5,
2,6-
10-1

在这一点上,我不会为新手难以阅读的正则表达式而烦恼。一个无正则表达式但冗长的纯js:解决方案

  • 我们用逗号分开
  • 我们修剪所有尾随空白
  • 我们检查每个部分是否有效
  • 当发现虚假范围时,我们返回false

演示:

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

在线试用!

最新更新