Search code examples
visual-studio-codecode-snippetsvscode-snippets

Plucking segment from VS Code path variable


I'm trying to write a snippet variable transform which will pluck a particular segment out of the path provided by TM_FILEPATH.

TM_FILEPATH: ~/Projects/folder/Dir/tests/Unit/FooTest.php

I need to grab Dir. I'm trying to use the following regex: \/([^\/]*)\/tests.

VS Code snippet transform:

${TM_FILEPATH/\\/([^\\/]*)\\/tests/$1/}

Actual output:

~/Projects/folderDir/Unit/FooTest.php

It seems that the transform is dropping the value of the full match, rather than replacing the variable with the first matching group, which is what I need.


Solution

  • Try:

    "${TM_FILEPATH/.*\\/([^\\/]*)\\/tests.*/$1/}",
    

    All I did was add a .* before and after your regex.

    The KEY POINT: For snippet transforms, if part of the variable is not included in the part to be transformed, it won't be transformed and so ends up in the final result.

    ${TM_FILEPATH/...part to be transformed.../$1/}
    

    So your regex was good, just most of the variable was not "signalled" to be transformed and so wasn't.