90

Imagine I have the following string :

set(SEXY_STRING "I love CMake")

then I want to obtain SEXY_LIST from SEXY_STRING so I can do

list(LENGTH SEXY_LIST len)

and len is equal 3.

I've found several macros on web, but I really want to know how to do it in "natural" way. This operation seems to be very basic and widely used.

NicholasM
  • 4,557
  • 1
  • 20
  • 47
Alexander K.
  • 1,649
  • 2
  • 15
  • 21

3 Answers3

92

Replace your separator by a ;. I don't see any other way to do it.

cmake_minimum_required(VERSION 2.8)

set(SEXY_STRING "I love CMake")
string(REPLACE " " ";" SEXY_LIST ${SEXY_STRING})

message(STATUS "string = ${SEXY_STRING}")
# string = I love CMake

message(STATUS "list = ${SEXY_LIST}")
# list = I;love;CMake

list(LENGTH SEXY_LIST len)
message(STATUS "len = ${len}")
# len = 3
tibur
  • 11,531
  • 2
  • 37
  • 39
48

You can use the separate_arguments command.

cmake_minimum_required(VERSION 2.6)

set(SEXY_STRING "I love CMake")

message(STATUS "string = ${SEXY_STRING}")
# string = I love CMake

set( SEXY_LIST ${SEXY_STRING} )
separate_arguments(SEXY_LIST)

message(STATUS "list = ${SEXY_LIST}")
# list = I;love;CMake

list(LENGTH SEXY_LIST len)
message(STATUS "len = ${len}")
# len = 3
Paweł Bylica
  • 3,780
  • 1
  • 31
  • 44
tillaert
  • 1,797
  • 12
  • 20
  • 1
    Using `separate_arguments()` in a `macro()` on Linux had to be `separate_arguments(args UNIX_COMMAND "${ARGS}")` if ARGS is the argument name for the macro. – Patrick B. Jul 01 '15 at 10:04
22
string(REGEX MATCHALL "[a-zA-Z]+\ |[a-zA-Z]+$" SEXY_LIST "${SEXY_STRING}")
Alexander K.
  • 1,649
  • 2
  • 15
  • 21
  • 1
    This may be a better solution. (Quote from http://www.cmake.org/cmake/help/v2.8.9/cmake.html) #REGEX MATCHALL will match the regular expression as many times as possible and store the matches in the output variable as a ***list***. – Nianliang Sep 16 '12 at 15:03
  • 1
    I'm using ***string(REGEX MATCHALL "([^\ ]+\ |[^\ ]+$)" ARG_LIST "${ARGN}")*** – Nianliang Sep 16 '12 at 15:05