String Range to Array Converter
Convert string ranges like "1-5, 8, 10-12" to arrays and back. Supports steps, negative numbers, descending ranges, and custom delimiters.
About
Handling number ranges in configuration files, pagination systems, or data pipelines introduces parsing ambiguity. A string like "1-5, 8, 10-12" must expand to exactly 9 discrete values, but edge cases - negative bounds, descending order, step intervals, duplicate elimination - cause silent data corruption if handled naively. This tool implements a bidirectional parser: it expands range strings into sorted, deduplicated arrays, and collapses integer arrays back into minimal range notation. The parser handles step syntax (e.g., 1-10:2), negative ranges (e.g., -5--1), and configurable delimiters. Approximation: this tool assumes integer-only inputs and does not handle floating-point ranges.
Formulas
The expansion algorithm for a range token A-B:S generates the set:
where d = sign(B โ A) determines direction (1 for ascending, โ1 for descending), and S defaults to 1 if omitted.
The collapse algorithm scans a sorted array and groups consecutive integers into range tokens. A consecutive sequence ai, ai+1, โฆ, aj where ak+1 โ ak = 1 for all k is collapsed to ai-aj only if (j โ i + 1) โฅ M, where M is the minimum range length (default 3).
Reference Data
| Input Pattern | Syntax | Example Input | Expanded Output | Notes |
|---|---|---|---|---|
| Single value | N | 5 | [5] | Passed through as-is |
| Simple range | A-B | 1-5 | [1,2,3,4,5] | Inclusive on both ends |
| Descending range | A-B where A > B | 5-1 | [5,4,3,2,1] | Produces descending order |
| Stepped range | A-B:S | 1-10:2 | [1,3,5,7,9] | Step S must be positive integer |
| Negative single | -N | -3 | [-3] | Leading minus sign |
| Negative range | -A--B | -5--1 | [-5,-4,-3,-2,-1] | Double dash separates negative bounds |
| Mixed signs | -A-B | -2-3 | [-2,-1,0,1,2,3] | Crosses zero boundary |
| Comma-separated list | A, B, C | 1, 3, 7 | [1,3,7] | Whitespace around commas ignored |
| Mixed list & ranges | A, B-C, D | 1, 3-5, 9 | [1,3,4,5,9] | Free mixing allowed |
| Duplicates | A, A | 1-3, 2-4 | [1,2,3,4] | Duplicates removed automatically |
| Large range | A-B | 1-1000 | [1,2,...,1000] | Capped at 100000 elements for safety |
| Collapse: consecutive | Array โ String | [1,2,3,5] | 1-3, 5 | Groups of โฅ3 collapsed by default |
| Collapse: single gaps | Array โ String | [1,2,5,6] | 1-2, 5-6 | Min range size configurable |
| Newline delimiter | One entry per line | 1-3\n5\n8-10 | [1,2,3,5,8,9,10] | Newline acts as comma |
| Semicolon delimiter | A;B | 1-3;5;8 | [1,2,3,5,8] | Custom delimiter support |