Excluding lines containing a specific string from REGEX REPLACE in CMake

岁酱吖の 提交于 2019-12-06 13:25:56

CMake's regex syntax and documentation are pretty limited. I'd favour turning the file's contents into a list of strings, each string being a line in the file. Iterating these makes the regex much simpler:

set(SourceFile "${CMAKE_SOURCE_DIR}/cfg/resources.cfg")
file(READ ${SourceFile} Contents)

# Set the variable "Esc" to the ASCII value 27 - basically something
# which is unlikely to conflict with anything in the file contents.
string(ASCII 27 Esc)

# Turn the contents into a list of strings, each ending with an Esc.
# This allows us to preserve blank lines in the file since CMake
# automatically prunes empty list items during a foreach loop.
string(REGEX REPLACE "\n" "${Esc};" ContentsAsList "${Contents}")

unset(ModifiedContents)
foreach(Line ${ContentsAsList})
  # Don't modify the line if it contains #local at the end.
  if(NOT "${Line}" MATCHES "#local${Esc}$")
    string(REGEX REPLACE "=.*/media" "=${OGRE_HOME_BACKSLASHES}/media" Line ${Line})
  endif()
  # Swap the appended Esc character back out in favour of a line feed
  string(REGEX REPLACE "${Esc}" "\n" Line ${Line})
  set(ModifiedContents "${ModifiedContents}${Line}")
endforeach()
file(WRITE ${SourceFile} ${ModifiedContents})

If you don't care about preserving blank lines, you can use file(STRINGS ...) to read in the file, which makes life a bit simpler:

set(SourceFile "${CMAKE_SOURCE_DIR}/cfg/resources.cfg")
file(STRINGS ${SourceFile} Contents)

unset(ModifiedContents)
foreach(Line ${Contents})
  # Don't modify the line if it contains #local at the end.
  if(NOT "${Line}" MATCHES "#local$")
    string(REGEX REPLACE
        "=.*/media"
        "=${OGRE_HOME_BACKSLASHES}/media"
        Line ${Line})
  endif()
  set(ModifiedContents "${ModifiedContents}${Line}\n")
endforeach()
file(WRITE ${SourceFile} ${ModifiedContents})

Probably the best description of CMake's regex syntax is found in the docs for string.

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