Does C# have built-in support for parsing strings of page numbers? By page numbers, I mean the format you might enter into a print dialog that\'s a mixture of comma and das
Here's something I cooked up for something similar.
It handles the following types of ranges:
1 single number
1-5 range
-5 range from (firstpage) up to 5
5- range from 5 up to (lastpage)
.. can use .. instead of -
;, can use both semicolon, comma, and space, as separators
It does not check for duplicate values, so the set 1,5,-10 will produce the sequence 1, 5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
public class RangeParser
{
public static IEnumerable Parse(String s, Int32 firstPage, Int32 lastPage)
{
String[] parts = s.Split(' ', ';', ',');
Regex reRange = new Regex(@"^\s*((?\d+)|(?\d+)(?(-|\.\.))(?\d+)|(?(-|\.\.))(?\d+)|(?\d+)(?(-|\.\.)))\s*$");
foreach (String part in parts)
{
Match maRange = reRange.Match(part);
if (maRange.Success)
{
Group gFrom = maRange.Groups["from"];
Group gTo = maRange.Groups["to"];
Group gSep = maRange.Groups["sep"];
if (gSep.Success)
{
Int32 from = firstPage;
Int32 to = lastPage;
if (gFrom.Success)
from = Int32.Parse(gFrom.Value);
if (gTo.Success)
to = Int32.Parse(gTo.Value);
for (Int32 page = from; page <= to; page++)
yield return page;
}
else
yield return Int32.Parse(gFrom.Value);
}
}
}
}