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.
Sean Bright : Voted up because I was 3 seconds from clicking post with the same answer :)David Brown : Thank you! In past attempts, I was enclosing each group in its own Zero or More expression, rather than nesting them.Jonathan Leffler : @sean.bright: thanks, and bad luck. There is still a fastest-gun-in-the-west problem, of sorts. :D -
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.
Jonathan Leffler : That allows 2.13.. as a valid number; also 2.13..13.Andrew Hare : Aha - you are correct! Nice catch! -
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;
Jonathan Leffler : When it works, very neat.
0 comments:
Post a Comment