Search code examples
c#regexsubstring

Extract version number


I am trying to just get the version number from an HML link.

Take this for example

firefox-10.0.2.bundle

I have got it to take everything after the - with

string versionNum = name.Split('-').Last();
versionNum = Regex.Replace(versionNum, "[^0-9.]", "");

which gives you an output of

10.0.2

However, if the link is like this

firefox-10.0.2.source.tar.bz2

the output will look like

10.0.2...2

How can I make it so that it just chops everything off after the third .? Or can I make it so that when first letter is detected it cuts that and everything that follows?


Solution

  • You could solve this with a single regex match. Here is an example:

    using System;
    using System.Text.RegularExpressions;
    
    public class Program
    {
        public static void Main()
        {
            Regex regex = new Regex(@"\d+.\d+.\d+");
            Match match = regex.Match("firefox-10.0.2.source.tar.bz2");
            if (match.Success)
            {
                Console.WriteLine(match.Value);
            }
        }
    }