Matching version number parts with regular expressions

后端 未结 6 2353
滥情空心
滥情空心 2021-02-15 14:28

I\'m trying to match the parts of a version number (Major.Minor.Build.Revision) with C# regular expressions. However, I\'m pretty new to writing Regex and even using Expresso is

相关标签:
6条回答
  • 2021-02-15 14:32

    Above answer not working properly

    (?<Major>\d*)\.(?<Minor>\d*)(\.(?<Build>\d*)(\.(?<Revision>\d*))?)?
    

    try this one,

      var regularExpression = @"^(\d+\.)?(\d+\.)?(\d+\.)?(\*|\d+)$";
                    var regex = Regex.IsMatch("1.0.0.0", regularExpression, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
                    Console.WriteLine(regex);
    
    0 讨论(0)
  • 2021-02-15 14:36
    (?<Major>\d*)\.(?<Minor>\d*)(\.(?<Build>\d*)(\.(?<Revision>\d*))?)?
    

    Makes the third and fourth parts optional.

    0 讨论(0)
  • 2021-02-15 14:39

    Try something like this:

    (?<Major>\d*)\.?(?<Minor>\d*)?\.?(?<Build>\d*)?\.?(?<Revision>\d*)?

    I simply added some "zero or one" quantifiers to the capture groups and also to the dots just in case they are not there.

    0 讨论(0)
  • 2021-02-15 14:42

    I know this isn't a regex, but System.Version does all the work for you.

    0 讨论(0)
  • 2021-02-15 14:56

    Tested in VBScript, this pattern:

    ^(\d+)(\.\d+)?(\.\d+)?(\.\d+)?$
    

    Will validate all the following True:

    • 23
    • 23.1
    • 23.1.1
    • 23.1.1.1

    And the following all False:

    • 23.11.11.33.11
    • 23.43 2.1
    • 44.11.2 3
    • 3q.4.2.1
    • 3.4.
    • 4.3.21a
    0 讨论(0)
  • 2021-02-15 14:56

    If you don't want to use Regex you could try:

    System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(<string filePath>);
    
    int major = fvi.FileMajorPart;
    int minor = fvi.FileMinorPart;
    int build = fvi.FileBuildPart;
    
    0 讨论(0)
提交回复
热议问题