简体   繁体   中英

Regular expression to validate version numbers

I need a regular expression to validate version numbers.

I have 4 types of version number:

  • 2015.1
  • 2015.1.01
  • 2015.1.01.1
  • 2015.1.01.1.RE

  • Group 1#: I need exactly 4 numbers

  • Group 2#: exactly 1 number
  • Group 3#: (1-2) numbers
  • Group 4#: (1-4) numbers
  • Group 5#: just RE

I already tried ^(\d+\.)?(\d+\.)?(\d+\.)?(\d+\.)?(\w+)$ but doesn't work.

string Expressao = @"^(\d+\.)?(\d+\.)?(\d+\.)?(\d+\.)?(\w+)$";
Regex Reg = new Regex(Expressao);
foreach(string rotulo in rotulos)
{
    Match result = Reg.Match(rotulo);
    if (result.Success)
    {
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(string.Format("Sucesso! {0}", rotulo), ConsoleColor.Green);
    }
    else
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(string.Format("Falha! {0}", rotulo), ConsoleColor.Green);
    }
}
Console.ReadKey();

How can I do this?

Your regex must be,

string Expressao = @"^\d{4}\.\d(?:\.\d{1,2}(?:\.\d{1,4}(?:\.RE)?)?)?$";

DEMO

Let's start out with the basics.

First, list the five groups

  1. [0-9]{4}
  2. [0-9]
  3. [0-9]{1,2}
  4. [0-9]{1,4}
  5. RE

Next, list the four variations

  1. [0-9]{4}\\.[0-9]
  2. [0-9]{4}\\.[0-9]\\.[0-9]{1,2}
  3. [0-9]{4}\\.[0-9]\\.[0-9]{1,2}\\.[0-9]{1,4}
  4. [0-9]{4}\\.[0-9]\\.[0-9]{1,2}\\.[0-9]{1,4}\\.RE

Finally, put them all together.

^([0-9]{4}\\.[0-9]|[0-9]{4}\\.[0-9]\\.[0-9]{1,2}|[0-9]{4}\\.[0-9]\\.[0-9]{1,2}\\.[0-9]{1,4}|[0-9]{4}\\.[0-9]\\.[0-9]{1,2}\\.[0-9]{1,4}\\.RE)$

This gives an working answer, but not a very nice one.

But knowing a little RE magic, you can create a nicer version. Here I linked optionals to chain together the full version.

^[0-9]{4}\\.[0-9](\\.[0-9]{1,2}(\\.[0-9]{1,4}(\\.RE)?)?)?$

If you are using c# then you can use Version.TryParse .

Sample:

string strVersion = "23.1.0";
if(Version.TryParse(strVersion, out Version version)
{
     // valid parsed.
}
else
{
    // invalid version.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM