Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two software version number using Regular Expression

Tags:

c#

regex

How to find latest version number using Regex ? for example

3.0.0.0 & 3.1.0.0

4.0.1.0 & 4.0.1.2

regards

anbu

like image 347
11 revs, 3 users 87% Avatar asked Mar 14 '26 14:03

11 revs, 3 users 87%


1 Answers

Why use regular expressions? They don't perform comparisons. However, System.Version not only will parse strings, but it supports comparisons:

// Use your favorite comparison operator
var current = new Version("4.0.1.2");
var found = new Version("4.0.1.0");
if (found > current)
{
    Console.WriteLine("Upgrade needed to {0} from {1}", found, current);
}
else
{
    Console.WriteLine("No upgraded needed from {0}", current);
}

Or if you have them in an enumeration, it works nicely with LINQ:

var versions = new [] { "3.0.0.0", "3.1.0.0", "4.0.1.0", "4.0.1.2" };
foreach (var version in versions.Select(Version.Parse)
                                .OrderByDescending(v => v))
{
    Console.WriteLine("{0}", version);
}

// Group them by Major Version first, then sort
foreach (var major in versions.Select(Version.Parse)
                              .GroupBy(v => v.Major)
                              .OrderByDescending(g => g.Key))
{
    Console.WriteLine("{0}: {1}",
                      major.Key,
                      String.Join(", ", major.OrderByDescending(v => v)));
}
like image 149
user7116 Avatar answered Mar 17 '26 04:03

user7116



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!