CMake: how to get the backslash literal in Regexp replace?
Solution 1
The reason is that in a CMake string literal, the backslash is an escape character (just like in C, Java or JavaScript) and in regex, the backslash is an escape character as well.
So to represent a regex as a string literal, you need double escaping. (That's why many "higher level" languages have regex literal notation, BTW.)
The string literal "\\"
represents the in-memory string "\"
and that's an invalid regex, hence the "ends in a backslash" error.
The string literal "\\\\"
represents "\\"
in memory which is a valid regex (representing a single backslash).
Solution 2
This is a simpler way to do it:
file(TO_NATIVE_PATH ${MYPATH} MYPATH)
Related videos on Youtube
WoutervD
Updated on May 13, 2022Comments
-
WoutervD about 2 years
I am trying to replace forwardslashes with backslashes. To do that i have the following line of code:
STRING(REGEX REPLACE "/" "\\" SourceGroup ${SourceGroupPath} )
SourceGroupPath = A/File/Path. SourceGroup is the variable to set the result to.
The problem i am having is with, the "\\" part to the code. I have tried several ways to getting to use the backslash literal like "\\" and using unicode but nothing seems to work.
The error i get in CMake is:
CMake Error at CMakeLists.txt:41 (STRING): string sub-command REGEX, mode REPLACE: replace-expression ends in a backslash.
Can someone please help me out?
Thanks,
Wouter
-
Tomalak over 13 yearsHave you tried
"\\\\"
?
-
-
Abid Rahman K about 10 yearswhat about forward slash?
-
Tomalak about 10 yearsThe forward slash has no meaning in regular expressions. It might have a meaning in the host language, but only if the host language uses forward slashes to delimit regex literals. In this case it must be escaped within the regex literal. (Many host languages work that way, so that you might come to think that the forward slash is somehow special in regular expressions. It's not.)
-
Maxim Suslov about 9 yearsResult is
string(REGEX REPLACE "/" "\\\\" SourceGroup ${SourceGroup})
-
Angew is no longer proud of SO about 9 yearsThe reasoning about need for double escapes is right, but this has nothing to do with C string literals - that's CMake code in the question, not C.
-
Tomalak about 9 years@Angew I take it that CMake strings work like C strings?
-
Angew is no longer proud of SO about 9 years@Tomalak In this regard, yes, the principle is the same - backslash is an escape character.
-
Antonio about 9 yearsHere is available the grammar description for cmake
-
Tomalak about 9 yearsOkay. In any case you are right, it was imprecise of me. I've corrected my post.
-
tresf almost 9 yearsSome build environments (such as MSYS) get mixed up and manual path conversion is needed due to 3rd party executables expecting non-posix style paths, hence the need for manual string replacement.