Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

regex - CMake: how to get the backslash literal in Regexp 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...