I am confused with a very simple example. I have a standard list, so basically its string representation uses semicolon as delimiters. I want to replace it by another one:
set(L1 "A" "B" "C")
message("L1: ${L1}")
string(REPLACE ";" "<->" L2 ${L1})
message("L2: ${L2}")
this snippet prints:
L1: A;B;C
L2: ABC
and I don't understand why. According to some other SO answers, my string replacement seems valid. What am I doing wrong ? Is there a way to store the value A<->B<->C
in my 2nd variable ?
Note: I use CMake 3.7.2
The solution is to use a regex: I.e. only replace ; if it is preceded by a non- \ character (and put that character in the replacement). The almost works, but it doesn't handle the first empty element because the semicolon isn't preceded by anything. The final answer is to allow the start of string too:
A list in cmake is a ; separated group of strings. To create a list the set command can be used. For example, set (var a b c d e) creates a list with a;b;c;d;e, and set (var "a b c d e") creates a string or a list with one item in it. (Note macro arguments are not variables, and therefore cannot be used in LIST commands.)
The almost works, but it doesn't handle the first empty element because the semicolon isn't preceded by anything. The final answer is to allow the start of string too: Oh and the \\ is because one level of escaping is removed by CMake processing the string literal, and another by the regex engine. You could also do this:
Just put ${L1}
in quotes:
set(L1 "A" "B" "C")
message("L1: ${L1}")
string(REPLACE ";" "<->" L2 "${L1}")
message("L2: ${L2}")
Otherwise the list will be expanded again to a space separated parameter list.
Reference
But ${L1}
isn't a string, it's a list. If you want a string then you need to enclose it in double-quotes like "${L1}"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With