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.
(?<Major>\d*)\.(?<Minor>\d*)(\.(?<Build>\d*)(\.(?<Revision>\d*))?)?
Makes the third and fourth parts optional.
I know this isn't a regex, but System.Version does all the work for you.
Tested in VBScript, this pattern:
^(\d+)(\.\d+)?(\.\d+)?(\.\d+)?$
Will validate all the following True:
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
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;
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);
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.