tags:

views:

724

answers:

3

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.

+6  A: 
(?<Major>\d*)\.(?<Minor>\d*)(\.(?<Build>\d*)(\.(?<Revision>\d*))?)?

Makes the third and fourth parts optional.

Jonathan Leffler
Voted up because I was 3 seconds from clicking post with the same answer :)
Sean Bright
Thank you! In past attempts, I was enclosing each group in its own Zero or More expression, rather than nesting them.
David Brown
@sean.bright: thanks, and bad luck. There is still a fastest-gun-in-the-west problem, of sorts. :D
Jonathan Leffler
A: 

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.

Andrew Hare
That allows 2.13.. as a valid number; also 2.13..13.
Jonathan Leffler
Aha - you are correct! Nice catch!
Andrew Hare
+1  A: 

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

System.Diagnostics.FileVersionInfo fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo();

int major = fvi.FileMajorPart;
int minor = fvi.FileMinorPart;
int build = fvi.FileBuildPart;

When it works, very neat.
Jonathan Leffler