I’m working on a WinForms app that accepts numeric strings as an input. If my user is entering a contiguous range of numbers, he/she may represent that range using a shorthand notation like this:
12[3-5]5550[000-100]
Using that example, I need to expand that string into the entire range of numbers that it encompasses like this:
1235550000
1235550001
1235550002
..........
1235550100
1245550000
1245550001
1245550002
..........
1245550100
1255550000
1255550001
1255550002
..........
1255550100
With the exception of 0-9, the strings will only contain [, – and ] which are the characters used to represent a range. As a part of the process of expanding the example string into individual numbers, I would like to validate the string, as well. For example, there must be an equal number of [ and ] characters. Inside of the brackets, the first number in the range must be less than the second number in the range. These types of things.
Is there an existing pattern that performs this kind of string manipulation?
There is nothing built in library in .net, that you can use. Your task is quite complex, considering that you want validation as well. I have created a small solution for generation of strings based on your initial input. Note this isn’t a production code and I have omitted some checks. This code only shown’s one possible way of how it could be done and is open to critique.
Tokenrepresent each logical piece of your string, which in your case either a literal, or a range specifier.Now usage is quite straightforward:
Prints: