Home > database >  CMake Regex Replace fails to compile
CMake Regex Replace fails to compile

Time:01-09

I'm trying to get the relative path of a file to a directory given absolute paths to the file and the containing directory by using string(REGEX REPLACE).

CMake is failing with the error:

CMake Error at CMakeLists.txt:74 (STRING):
  STRING sub-command REGEX, mode REPLACE failed to compile regex
  "^C:/AnchyDev/Projects/C  /AzerothCore/AzerothCore/".

The error only appears when trying to add a module to the source, removing the module lets CMake configure correctly.

CMake function:

# add modules and dependencies
CU_SUBDIRLIST(sub_DIRS  "${CMAKE_SOURCE_DIR}/modules" FALSE FALSE)
FOREACH(subdir ${sub_DIRS})

    get_filename_component(MODULENAME ${subdir} NAME)

    if (";${DISABLED_AC_MODULES};" MATCHES ";${MODULENAME};")
        continue()
    endif()

    STRING(REGEX REPLACE "^${CMAKE_SOURCE_DIR}/" "" subdir_rel ${subdir}) # THE CULPRIT

    if(EXISTS "${subdir}/CMakeLists.txt")
        add_subdirectory("${subdir_rel}")
    endif()
ENDFOREACH()

I have tried clearing CMake cache. I am using CMake version 3.25.1.

CodePudding user response:

The issue is the part of your regular expression. The character in regex is a matching operator that matches one or more of the previous pattern (which in this case is the character "c").

A correct regex for what you are trying to do is one where the literal characters are escaped with backslashes. i.e. you'd need to do a string replacement on your file path which you are using as a regular expression to replace instances of with \ . But in general, that's not a good approach because there are other regular expression operators you'd have to worry about.

Another option to do what you want (as you've shown in your self-answer) is to just use plain string replacement instead of regex string replacement, but that won't capture the part about only replacing prefix matches.

What you are actually looking for is probably the file(RELATIVE_PATH) command, which would be used in your case like this:

file(RELATIVE_PATH subdir_rel "${CMAKE_SOURCE_DIR}" "${subdir}")

CodePudding user response:

I fixed it by removing the regex since it is just a simple replace.

Before: STRING(REGEX REPLACE "^${CMAKE_SOURCE_DIR}/" "" subdir_rel ${subdir}) # THE CULPRIT

After: STRING(REPLACE "${CMAKE_SOURCE_DIR}/" "" subdir_rel ${subdir}) # THE CULPRIT

Thanks Foe for the fix.

  • Related