Reputation: 103
I need Regular Expression that validates the page ranges. (Eg. Print custom pages)
Currently, I have tried this expression
/^(?!([ \d]*-){2})\d+(?: *[-,] *\d+)*$/
It should accept values like
1, 3, 6-9
1-5, 5
6, 9
It should not accept values like
,5
5-,9
9-5,
2,6-
10-1
Upvotes: 3
Views: 1141
Reputation: 23541
At that point I wont bother with a regex hard to read by a neophyte. A regex-free, but verbose, solution with pure js:
Demo:
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"))
Upvotes: 5