Extract version number from string(eg : “ver.1.9.0”)

后端 未结 3 564
盖世英雄少女心
盖世英雄少女心 2021-01-29 05:19

if i pass a string (verstring == \"vername.1.19.5\") it will return the version because i am ignoring Currentver[0]. if i want to pass verstring == \"1.19.5\".

I mean i

相关标签:
3条回答
  • 2021-01-29 06:05

    Why making life harder as it already is?

    string v = verstring.Replace(':','.').Substring(5,verstring.Length);
    

    Now you don't need to care about whether it actually is separated by : or . you can simply split by .:

    currentVer = v.Split('.');
    a= Convert.ToByte(currentVer[1]);
    b= Convert.ToByte(currentVer[2]);
    c= Convert.ToByte(currentVer[3]);
    
    0 讨论(0)
  • 2021-01-29 06:09

    Here you go:

    using System;
    using System.Text.RegularExpressions;
    
    namespace RegVer {
        class Prog {
            static void Main() {
                var verstring = "ver:1:9.5";
                var dotVerString = verstring.Replace(':','.');
                Console.WriteLine(Regex.Match(dotVerString, @"ver\.([\d\.]+)").Groups[1].Value);
            }
        }
    }
    

    Or if you want array with each version digit.

    using System;
    using System.Text.RegularExpressions;
    
    namespace RegVer {
        class Prog {
            static void Main() {
                var verstring = "ver:1:9.5";
                var VerABC = Regex.Matches(verstring, @"\d");
                Console.WriteLine("a = " + VerABC[0] + "\n" +
                                  "b = " + VerABC[1] + "\n" +
                                  "c = " + VerABC[2]);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-29 06:12

    If you are opened to use Regex, the answer below might help you:

    var regexPattern = @"(?:ver\:)?(?<major>\d)[\.|\:](?<minor>\d)[\.|\:](?<revision>\d)";
    var regex = new Regex(regexPattern);
    
    var match = regex.Match("1:2.3");
    var major = Convert.ToByte(match.Groups["major"].Value);
    var minor = Convert.ToByte(match.Groups["minor"].Value);
    var revision = Convert.ToByte(match.Groups["revision"].Value);
    

    It uses regex named groups in order to retrieve the value versions. You can change the group name as part of the regex by a,b,c if you prefer and you would get something like this:

    var regexPattern = @"(?:ver\:)?(?<a>\d)[\.|\:](?<b>\d)[\.|\:](?<c>\d)";
    var regex = new Regex(regexPattern);
    
    var match = regex.Match("1:2.3");
    var a = Convert.ToByte(match.Groups["a"].Value);
    var b = Convert.ToByte(match.Groups["b"].Value);
    var c = Convert.ToByte(match.Groups["c"].Value);
    
    0 讨论(0)
提交回复
热议问题