Matching version number parts with regular expressions

倖福魔咒の 提交于 2019-12-03 13:46:23
(?<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.

Daz_1234

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
Perry Neal

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!