I need a regex for page sequences that
matches:
but doesn't match:
I have tried the following patterns but they don't work:
/^(\d*-\d*,?|\d*,?)*$/
/^(\d*-{1}\d*,?|\d*,?)*$/
I also want to validate user input while the user types, so the pattern needs to allow tailing - and , in certain cases. The example React code for allowing input with a particular pattern looks like this:
const customPageInputChange = (e) => {
if(e.target.value.match(/.../) !== null) {
setCustomPage(e.target.value)
}
}
See https://jsfiddle.net/mayankshukla5031/4zqwq1fj/ for a full example with input validation.
One possible regex:
^(\d+(-\d+)?, )*\d+(-\d+)?$
See https://regex101.com/r/txVh3e/1 for test cases.
If you also want to check whether the pages are increasing, a regex is not really suitable, and you should opt for checking the strings programmatically.
If you want to validate user input while the user is typing, you need a regex allowing trailing - and ,. One possible regex:
^(\d+(-\d+)?, ?)*(\d+-?\d*)?$
See https://regex101.com/r/rKx6lq/1 for test cases and https://jsfiddle.net/qtb4yd7s/ for a demo.
You might use
^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$
In Javascript you can use regex.test(str) to return a boolean to see if the pattern matched.
In parts, the pattern matches:
^ Start of string\d+ Match 1+ digits(?:-\d+)? Optionally match - and 1+ digits(?: Non capture group to match as a whole part
,\s* Match a comma and optional whitespace chars\d+(?:-\d+)? The same as previous pattern)* Close the non capture group and optionally repeat to als match a single occurrence$ End of stringSee a Regex demo