Skip to content

file(STRINGS ... REGEX) fails to populate CMAKE_MATCH_<n> with subexpressions

file(STRINGS ... REGEX) fails to populate CMAKE_MATCH_ with subexpressions; making it or the documentation errant

https://cmake.org/cmake/help/latest/command/string.html#regex-specification specifies

All regular expression-related commands, including e.g. if(MATCHES), save subgroup matches in the variables CMAKE_MATCH_ for 0..9.

Setup

  • Windows 10 with current updates
  • cmake 3.19.1

Repro

file(STRINGS "${DIR}/${SINGLE_FILE}" RESULTS REGEX "something \"([^\"]+)\"")
message(STATUS "list: ${RESULTS}")           # contains list
message(STATUS "match0: ${CMAKE_MATCH_0}")   # bug, it is empty, should be last match
message(STATUS "match1: ${CMAKE_MATCH_1}")   # bug, it is empty, should be last submatch

Result

CMAKE_MATCH_0and CMAKE_MATCH_1 are not populated

Expected

CMAKE_MATCH_0and CMAKE_MATCH_1 are populated with last matches

Notes

By doc/spec the last match and submatch should be in the CMAKE_MATCH_<n> vars.

However, the intention is to generate a list of matches and list of the submatches; a new feature/behavior that is not spec/doc'd

Workarounds...

  • file(READ) into a var and the string(REGEX) that variable
  • file (STRINGS REGEX) into a var, foreach() that var and string(REGEX) into a list
  • etc
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information