CMake:如何获取正则表达式替换中的反斜杠文字?
我正在尝试用反斜杠替换正斜杠。 为此,我有以下代码行:
STRING(REGEX REPLACE "/" "\\" SourceGroup ${SourceGroupPath} )
SourceGroupPath = A/File/Path。 SourceGroup 是要设置结果的变量。
我遇到的问题是代码的“\\”部分。 我尝试了几种方法来使用反斜杠文字,例如“\\” 并使用 unicode 但似乎没有任何效果。
我在 CMake 中遇到的错误是:
CMakeLists.txt 中的 CMake 错误:41 (STRING):字符串子命令REGEX, 模式 REPLACE:替换表达式结束 在反斜杠中。
有人可以帮我吗?
谢谢,
沃特
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
原因是在 CMake 字符串文字中,反斜杠是转义字符(就像在 C、Java 或 JavaScript 中一样),而在正则表达式中,反斜杠也是转义字符。
因此,要将正则表达式表示为字符串文字,您需要双重转义。 (这就是为什么许多“高级”语言都有正则表达式文字表示法,顺便说一句。)
字符串文字
"\\"
表示内存中的字符串"\"
这是一个无效的正则表达式,因此出现“以反斜杠结尾”错误。字符串文字
"\\\\"
表示内存中的"\\"
,它是一个有效的正则表达式(代表单个反斜杠)。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).这是一种更简单的方法:
This is a simpler way to do it: