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
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?
Let's start out with the basics.
First, list the five groups
[0-9]{4}
[0-9]
[0-9]{1,2}
[0-9]{1,4}
RE
Next, list the four variations
[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
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.