[CMake] SUBSTRING - STRING - shorten a string variable

Brandon Van Every bvanevery at gmail.com
Mon Dec 3 17:22:10 EST 2007


On Dec 3, 2007 4:12 PM, Sören Freudiger <muffmolch at gmx.de> wrote:
> No, it's the other way around.
>
> e.g.
> CMAKE_CURRENT_SOURCE_DIR =
> "E:/LBM_subversion/source/topology/amr3d/lbmd3q19/singlephase/testcases/RCF/
> all_in_one"
>
> And I'm looking for
> Path="E:/LBM_subversion/source/"
>
> And the keyword I'm looking for is:
>
> "/source/"
> That's the only keyword that's possible...
> The path to source can be different and also the path to the CMakeLists.txt
> (depend on the project and the machine I'm on).

# Typically you need to do a MATCH to verify you've got what you're
interested in,
# then a REGEX REPLACE to extract the arguments.  It's not safe to do the
# REGEX REPLACE without first doing a MATCH.  If the string doesn't actually
# match, the REGEX REPLACE will give you an unmodified original string.  You
# probably want a null string in that case, not an unmodified original string.
#
# I typically set the regex in advance, so that I'm certain I'll
always use it for
# both the MATCH and the REGEX REPLACE.  If I change my regex in the
# future, there's only 1 place to edit it.

set(source_regex "(.*)/source/(.*)")
string(REGEX MATCH
  "${source_regex}"
  source_path "${CMAKE_CURRENT_SOURCE_DIR}")
if(source_path)
  string(REGEX REPLACE
    "${source_regex}"
    "\\1"
    before_source "${source_path}")
  string(REGEX REPLACE
    "${source_regex}"
    "\\2"
    after_source "${source_path}")
endif(source_path)

# Note: if /source/ appears twice in your string, you're screwed!
# Safer to use only one (.*) so that the greedy regex expansion
# goes in a predictable direction.

set(source_and_after_regex "/source/(.*)")
# Note that a path ending in "/source" without a / could screw you up.
# Handling that is left as an exercise to the reader.
string(REGEX MATCH
  "${source_and_after_regex}"
  source_and_after "${CMAKE_CURRENT_SOURCE_DIR}")
if(source_and_after)
  string(REGEX REPLACE
    "${source_and_after_regex}"
    "\\1"
    after "${source_and_after}")
  # REPLACE replaces all occurrances, not just one.
  # Sometimes this causes problems.  In this case it does not,
  # because we know that "/source/(.*)" contains every possible
  # instance of "/source/" in the string.  There is only 1 possible
  # REPLACE.
  string(REPLACE
    "${source_and_after}"
    ""
    before "${CMAKE_CURRENT_SOURCE_DIR}")
endif(source_and_after)


Cheers,
Brandon Van Every


More information about the CMake mailing list