Home > Blockchain >  How get string inside bracket "()" using cmake regex
How get string inside bracket "()" using cmake regex

Time:11-30

I am trying to get the string inside '( )' by using CMake regex. here is the example which I tried:

set(STR "example(arg1,arg2)")
string(REGEX MATCH "^\(.*\)$" ARG_STR ${STR}) 

expected: arg1,arg2, but I got example(arg1,arg2) Please guide me how to fix this.

CodePudding user response:

You can use a capturing group with a pattern lie

string(REGEX MATCH "\\(([^()]*)\\)" _ ${STR}) 

Then, you can access the contents using ${CMAKE_MATCH_1}, e.g.

message("ARGS_STR: ${CMAKE_MATCH_1}")

See CMAKE reference details:

New in version 3.9: All regular expression-related commands, including e.g. if(MATCHES), save subgroup matches in the variables CMAKE_MATCH_ for <n> 0..9.

Also, see the regex demo.

CodePudding user response:

The question was already answered correctly. But I'd like to show an easy way to also add error checking in case the regex fails.

set(STR "example(arg1,arg2)")

if (${STR} MATCHES "\\(([^()]*)\\)")
    message(STATUS ${CMAKE_MATCH_1})
else()
    message(FATAL_ERROR "Regex failed!")
endif()
  • Related