[CMake] Problems with REGEX REPLACE

Wim Dumon wim at emweb.be
Sat Mar 14 11:31:01 EDT 2009


Hi,

I have some files which contain lines like this:
int a() {
  print "foo";
  do "bar";
}
Which I want to convert into a C-style string, so I want to start with
some transformations that would turn this file into something like:
char *myFile =
"int a() {"
"  print \"foo\";"
"  do \"bar\";"
"}";

Currently we're using a small C++ program that does this, but for
cross-compilation simplicity I was considering to replace this with a
CMake script. I managed to write this transformation in sed, but not
in cmake, and after a short look at the cmake code
(cmStringCommand.cxx), I gave up. Is what I want possible with cmake?

The errors produced are similar to:
   string sub-command REGEX, mode REPLACE: Unknown escape "\""in
   replace-expression.

   string sub-command REGEX, mode REPLACE regex "^" matched an empty string.

Best regards,
Wim.

cmake_minimum_required(VERSION 2.6)

# The equivalent of: sed s/\"/\\\\\"/g | sed s/^/\"/ | sed s/$/\"/
FOREACH(file a.js b.js)
  FILE(READ ${file} f0)
  # Does not work: \" is not valid in replacement string
  STRING( REGEX REPLACE "\"" "\\\"" f1 "${f0}")
  # Does not work: ^ matches an empty string and is for obscure reasons invalid
  # Additionally, \" is not valid in replacement string
  STRING( REGEX REPLACE "^" "\"" f2 "${f1}")
  # Does not work: $ matches an empty string and is for obscure reasons invalid
  # Additionally, \" is not valid in replacement string
  STRING( REGEX REPLACE "$" "\"" f3 "${f2}")
  # Alternative: does not work: \" is not a valid escape in replacement string
  #STRING( REGEX REPLACE "\n" "\"\n\"" f2 "${f1}")
  FILE(WRITE ${file}.cc "${f3}")
ENDFOREACH(file)


More information about the CMake mailing list