CMake:如何获取反斜杠文字在Regexp中替换? [英] CMake: how to get the backslash literal in Regexp replace?
问题描述
我尝试用反斜线替换正斜杠。为了做到这一点,我有以下代码行:
STRING(REGEX REPLACE/\\\ \\SourceGroup $ {SourceGroupPath})
SourceGroupPath = A / File /
SourceGroup是将结果设置为的变量。
我遇到的问题是,代码的\\部分。
我尝试了几种方法来使用反斜杠文字像\\
和使用unicode,但没有什么似乎工作。
CMake错误在CMakeLists.txt:41
(STRING)命令REGEX,
mode REPLACE:replace-expression以反斜杠结尾
。
感谢,
Wouter
原因是在CMake字符串文字中,反斜杠是一个转义字符(就像在C,Java或JavaScript中),在regex中,反斜杠是一个转义字符井。
因此,要将正则表达式表示为字符串字面值,需要双重转义。 (这就是为什么许多较高级别语言具有正则表达式符号,BTW。)
字符串文字 \\\
表示内存中字符串\
,这是一个无效的正则表达式,因此结束于反斜杠错误。
字符串文字\\\\
代表\\ \\\
在内存中,这是一个有效的正则表达式(表示单个反斜杠)。
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
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).
这篇关于CMake:如何获取反斜杠文字在Regexp中替换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!