0

I'm sorry if this seems like a noob question but I have problems understanding this command properly and Google didn't help me.

Say I have this CMake script:

set (OUTDIR ${CMAKE_CURRENT_BINARY_DIR}/MyFolder) string (REGEX REPLACE "/" "\" OUTDIR ${OUTDIR})

I found a similar example in a book. I tried reading the explanation there along with the documentation but it's still not entirely clear to me what that snippet does. As I understand from the documentation: REGER REPLACE will replace "/" with "\" every time it finds it and returns the result in the output. So in this case the output would be what? The 'OUTDIR' folder which is the path defined above with set? I do not understand why it's 'OUTDIR ${OUTDIR}' and not simply '${OUTDIR}'. Please help me clear this confusion by explaining that snippet. Thank you

Kennedy
  • 277
  • 2
  • 7
  • 21

1 Answers1

0

You understood almost correct the first part. The thing is that the first two string literals after REGEX REPLACE are two RegExes (Regular Expressions). So this function will find all the matches of the first RegEx in the last string you specified, and will replace them with the value coming from the second RegEx. The result will be saved in that string-variable before the last.

Now, in Regular Expressions, some characters have a special meaning, they are named special characters. The backslash is one of them. If you want this character to be treated as a normal character, you must escape it, putting a backslash before it.

Now, in a CMake string literal you must also escape the backslash character, putting another backslash before it.

That being said, in order for your code to replace in OUTDIR all / with \ you would want to write like this:

set (OUTDIR ${CMAKE_CURRENT_BINARY_DIR}/MyFolder)
string (REGEX REPLACE "/" "\\\\" OUTDIR ${OUTDIR})

This is a related question: CMake: how to get the backslash literal in Regexp replace?

You can learn more about RegEx here: https://www.regular-expressions.info

Sebi
  • 428
  • 5
  • 11
  • thank you. It makes sense now. So it looks for first expression and replaces it with the second one in ${OUTDIR} after it expands it and stores the result in OUTDIR variable :D. – Kennedy Jan 30 '18 at 07:57
  • Can you please explain to me what this command is supposed to do? I can't get my head around that first complicated argument: string(REGEX REPLACE ".*v[0]*\([0-9]+\)\\.[0]*\([0-9]+\)\\.[0]*\([0-9]+\).*" "\\1" MY_VAR ${MY_VAR} ) – Kennedy Feb 02 '18 at 07:54
  • After _"REGEX REPLACE"_, the first argument is a RegEx. From what I understand it detects a version number. You can check it here: https://regex101.com/r/cOqM9g/1 The second RegEx is wrong. If you want to replace the version with the number 1 it should only be "1", not "\\1" since 1 is not a special character, thus not needed to be escaped. – Sebi Feb 02 '18 at 12:37