4

I want to validate user-specified version string - to ensure it consists of three period-separated numbers (e.g. 1.20.300).
But i'm not sure how to write such regex, the code below is just a try:

if( PROJECT_VERSION MATCHES "([0-9]+).([0-9]+).([0-9+])" )
    message( "NOTE: Valid version string" )
else()
    message( FATAL_ERROR "Invalid version string" )
endif()

So, how to correctly write required regex?
Thanks.

UPD
My regex also matches 1.2.3.4, but is should not!
Only three period-separated numbers are possible.

eraxillan
  • 1,552
  • 1
  • 19
  • 40

1 Answers1

11

Dots are special in regex, so you should escape them:

"^([0-9]+)\\.([0-9]+)\\.([0-9]+)$"

Why double-backslash? See here: https://stackoverflow.com/a/4490920/4323

Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • Ok, looks like it works! :) Can you briefly explain why you use `^` and `$`? Also, i still can't understand what regex syntax dialect CMake supports. E.g. there is no `\d` (any digit) operator here – eraxillan Nov 02 '15 at 12:14
  • 1
    `^` and `$` mean "beginning" and "end" of the string respectively. This prevents matching rubbish like abc1.2.3xyz. – John Zwinck Nov 02 '15 at 13:59
  • Got it. This is the reason why my original regex matches 1.2.3**.4**. Thanks! – eraxillan Nov 02 '15 at 14:09