PageRange.parse constructor

PageRange.parse(
  1. String rangeString
)

Parses a page range string (e.g., "1-3,5,7-9") into a PageRange object.

Throws an ArgumentError if the format is invalid.

Implementation

factory PageRange.parse(String rangeString) {
  final trimmed = rangeString.trim();
  if (trimmed.isEmpty) {
    throw ArgumentError('Page range string cannot be empty.');
  }
  // A simple regex to validate the overall structure. It's not exhaustive but catches most common errors.
  final RegExp validPageRange = RegExp(r'^\s*\d+(-\d+)?(\s*,\s*\d+(-\d+)?)*\s*$');
  if (!validPageRange.hasMatch(trimmed)) {
    throw ArgumentError('Invalid page range format: "$rangeString". Use a format like "1-3,5,7-9".');
  }
  // Further validation could be added here (e.g., check if end > start in all sub-ranges).
  return PageRange._(trimmed);
}