Matching version number parts with regular express

2020-06-16 02:54发布

问题:

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 proving to be a little difficult. Right now, I have this:

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

This works, but requires that every part of the version number exists. What I would like to do is also match versions like:

2.13

In this case, the Build and Revision groups need to return null values. Feel free to suggest a better method if I'm going about this all wrong.

回答1:

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

Makes the third and fourth parts optional.



回答2:

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



回答3:

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


回答4:

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;


回答5:

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);


回答6:

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.



标签: c# regex version