Satheesh Kurunthiah
Satheesh Kurunthiah

Reputation: 15

usage of regular expression on numbers

User gives input like 4.0.9

I have a list of such numbers in a file like 4.0.8, 4.0.9, 4.0.10 etc. In this case i have to select 4.0.9 out of this three.

But if the file contains like 4.0.8, 4.0.9+, 4.0.10 then I have to copy both 4.0.9 and 4.0.10.

Also if it has like 4.0.8, 4.0.9, 4.0.10+ then I have to copy only 4.0.9

I tried with regular expression in c# but doesn't suite for all test case. Any idea how to implement this logic or any in-build function available?

Upvotes: 1

Views: 90

Answers (1)

Konrad Kokosa
Konrad Kokosa

Reputation: 16878

If I understand you requirements correctly, you can write it in the following way. Assuming you have some list of versions (unsorted), you can parse it to the helper list. Notice that I'm additionaly sorting versions from the list, to make logic clearer:

string list = "4.0.8, 4.0.9+, 4.0.10";
var versions =
list.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
    .Select(s => new
    {
       Version = Version.Parse(s.TrimEnd('+')),
       FutureReleases = s.EndsWith("+")
    })
    .OrderBy(a => a.Version);

Then simply iterate through it when matching some specific input:

string input = "4.0.9";
var version = Version.Parse(input);
var output = versions.SkipWhile(a => a.Version < version);
var first = output.FirstOrDefault();
if (first != null && !first.FutureReleases)
{
    output = versions.TakeWhile(a => a.Version == version);
}

Here we are just omitting lower version and take single version (if + was not specified) or all higher additionally (if + was specified).

Upvotes: 1

Related Questions