Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex pattern to match valid version numbers

Tags:

regex

I'm looking for a regex pattern that would match a version number.

The solutions I found here don't really match what I need.

I need the pattern to be valid for single numbers and also for numbers followed by .

The valid numbers are

1
1.23
1.2.53.4

Invalid numbers are

01
1.02.3
.1.2
1.2.
-1
like image 922
Ziko Avatar asked Jan 02 '23 02:01

Ziko


1 Answers

Consider:

^[1-9]\d*(\.[1-9]\d*)*$

Breaking that down:

  • ^ - Start at the beginning of the string.
  • [1-9] - Exactly one of the characters 1 thru 9.
  • \d* - More digits.
  • ( - Beginning of some optional extra stuff
  • \. - A literal dot.
  • [1-9] - Exactly one of the characters 1 thru 9.
  • \d* - More digits.
  • ) - End of the optional extra stuff.
  • * - There can be any number of those optional extra stuffs.
  • $ - And end at the end of the string.

Beware

Some of this syntax differs depending what regex engine you are using. For example, are you using the one from Perl, PHP, Javascript, C#, MySQL...?

In my experience, version numbers do not fit the neat format you described.

Specifically, you get values like 0.3RC5, 12.0-beta6, 2019.04.15-alpha4.5, 3.1stable, V6.8pl7 and more.

If you are validating existing data, make sure that your criteria fit the conditions you've described. In particular, if you are following "Semantic Versioning", be aware that versions which are zeros are legal, so 1.0.1, that "Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.", and that "1" is not a legal version number.

Be warned that the above will also match stupidly long version numbers like 1.2.3.4.5.6.7.8.9.10.11.12.13.14. To prevent this, you can restrict it, like so:

^[1-9]\d*(\.[1-9]\d*){0,3}$

This changes the * for "any number of optional extra dots and numbers" to a range from zero to three. So it'd accept 1, 1.2, 1.2.3, and 1.2.3.4, but not 1.2.3.4.5.

Also, if you want zeros to be legal but only if there are no other numbers (so 0.3, 1.0.1), then it gets a little more complex:

^(0|[1-9]\d*)(\.(0|[1-9]\d*)){0,3}$

This question may also be a duplicate: A regex for version number parsing

like image 177
Dewi Morgan Avatar answered Jan 11 '23 20:01

Dewi Morgan