How to remove a line of text in a string in CMake, working around CMake's lack of line-based regex matching?

爱⌒轻易说出口 提交于 2021-01-28 02:04:25

问题


I found out that CMake doesn't do RegEx the way I expected. Apparently, others have had this same problem as well. The issue is that CMake is not line-based. When you use the ^ or the $ operators, they work against the entire string, not the start and end of a line.

I'm trying to remove all the lines in a file that say #include <blah.h> or #include "blah.h".

To do so, I whipped up a little function:

function(deleteinplace IN_FILE pattern)
    file(READ ${IN_FILE} CONTENTS)
    string(REGEX REPLACE ${pattern} "" STRIPPED ${CONTENTS})
    file(WRITE ${IN_FILE} "${STRIPPED}")
endfunction()

Then to call it:

deleteinplace(myfile.h "\#include.*\n")

This ends up removing everything in the file after the string is matched.

Non-Greedy tricks like .*? don't work in CMake for some reason. Other tricks like \r?\n also do not work.

I need a work around for this.


回答1:


The trick is not to use file(READ ...), but file(STRINGS ....). This will let CMake read file line by line, and return a list of strings representing one line each, exactly as you need. Using this approach, your function would look like this:

function(deleteinplace IN_FILE pattern)
  # create list of lines form the contens of a file
  file (STRINGS ${IN_FILE} LINES)

  # overwrite the file....
  file(WRITE ${IN_FILE} "")

  # loop through the lines,
  # remove unwanted parts 
  # and write the (changed) line ...
  foreach(LINE IN LISTS LINES)
    string(REGEX REPLACE ${pattern} "" STRIPPED "${LINE}")
    file(APPEND ${IN_FILE} "${STRIPPED}\n")
  endforeach()
endfunction()

Then to call it:

deleteinplace(myfile.h "\#include.*")

Note that in this example \n is automatically stripped from the lines as a partt of file(STRINGS ....) statement, and added back within file(APPEND ....) statement; therefore, \n was also removed from the search pattern when calling the function.

At the end, here is the documentation about file(STRINGS ...)



来源:https://stackoverflow.com/questions/59494184/how-to-remove-a-line-of-text-in-a-string-in-cmake-working-around-cmakes-lack-o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!