CMake删除前两个字符正则表达式?

时间:2014-06-15 02:10:09

标签: regex cmake

我有一个变量,包含两个由空格分隔的包含路径:

PATHS=-I/home/user/application_x/include -I/home/user/application_y/include

我想将其拆分为两个变量,然后删除-I。这是我到目前为止所提出的:

STRING(REGEX MATCH "[^ ]*" APPLICATION_X ${PATHS})
STRING(REGEX MATCH "[^ ]*$" APPLICATION_Y ${PATHS})

结果:

APPLICATION_X=-I/home/user/application_x/include
APPLICATION_Y=-I/home/user/application_y/include

如何从每个字符串中删除-I?文件夹名称'application_x'和'application_y'不是静态的,因此只应删除第一次出现的-I,否则如果文件夹名为'application_-I',一切都会中断。

如果可以分割变量并在每个路径的一个正则表达式中删除-I,那么这将是首选。

2 个答案:

答案 0 :(得分:4)

您可以使用REGEX MATCH

执行以下操作
STRING(REGEX MATCH "/[^ ]*"  APPLICATION_X ${PATHS})
STRING(REGEX MATCH "/[^ ]*$" APPLICATION_Y ${PATHS})

或者您可以使用REGEX REPLACE

STRING(REGEX REPLACE "-I([^ ]*)" "\\1"  APPLICATION_X ${PATHS})
STRING(REGEX REPLACE "-I([^ ]*)$" "\\1" APPLICATION_Y ${PATHS})

答案 1 :(得分:1)

使用REGEX REPLACE接受的答案对我不起作用(由于某种原因,cmake 3.0.2始终返回${PATHS}的完整内容。

根据cmake文档,您还可以使用$ {CMAKE_MATCH_1}找到该群组:

()    Saves a matched subexpression, which can be referenced
      in the REGEX REPLACE operation. Additionally it is saved
      by all regular expression-related commands, including
      e.g. if( MATCHES ), in the variables CMAKE_MATCH_(0..9).

对于你的例子,它将是:

STRING(REGEX MATCH "-I([^ ]*)"  APPLICATION_X ${PATHS})
set(APPLICATION_X ${CMAKE_MATCH_1})
STRING(REGEX MATCH "-I([^ ]*)$" APPLICATION_Y ${PATHS})
set(APPLICATION_Y ${CMAKE_MATCH_1})