A page-selection field looks small until you ask what should happen with 1, , 2junk , or 1-1000,1 . A forgiving parser might quietly keep the part it understands. For a document operation, that can leave the user with a different selection from the one they meant.
This example takes a narrower approach: under an explicit teaching policy, it accepts the entire input or returns null . It converts displayed page numbers, which start at one, into zero-based indices. It does not open or modify a PDF.
Define the contract before parsing
The grammar accepts ASCII positive integers and inclusive ranges separated by commas. Whitespace is allowed around tokens but not inside a range. Descending ranges are valid. If a page occurs more than once, the output keeps its first occurrence, so 4-2,2,6 becomes [3,2,1,5] for a six-page document.
The policy rejects leading zeroes, full-width digits, semicolons, empty tokens, trailing text, and out-of-range pages.…