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

How to use Regex to return a directory from TM_FILEPATH in vscode user snippets?


I am looking for a way to create a user snippet to grab the core directory from a project. Here is the sample path that I am using:

C:dev/Pseudope/Unreal/Cubicle/Source/CubicleCore/Private

When creating vscode snippets ${TM_FILEPATH} will return this path to be used along side a regular expression. I want to be able to use these snippets for different projects that will all have the same structure as the filepath above where the text that I want to apply to the snippet will always be nested between Source and Private|Public. Here is the regex that I have so far:

(?<=Source\\)(.*)(?=\\Private|Public)

According to https://regexr.com/ this expression will target the value "CubicleCore" as well as group it into group 1. Unfortunately, there seems to be a disconnect between the regular expression in the browser and how vscode is interpreting it because the result I get is:

UE_LOG(Log${TM_FILEPATH/(?<=Source\)(.*)(?=\Private|Public)/}, Log, TEXT("Hello");

When it should be:

UE_LOG(LogCubicleCore, Log, TEXT("Hello");

Any help/direction would be greatly appreciated.


Solution

  • You can use

    "UE_LOG(Log${TM_FILEPATH/.*Source[\\\\\\/]([^\\\\/]+)[\\\\\\/](?:Private|Public).*/$1/}, Log, TEXT(\"Hello\")"
    

    See the regex demo.

    Details:

    • .* - any zero or more chars as many as possible
    • Source - Source
    • [\\\/] - / or \
    • ([^\\\/]+) - Group 1 ($1): any one or more chars other than \ and /
    • [\\\/] - a / or \ char
    • (?:Private|Public) - Private or Public string
    • .* - any zero or more chars as many as possible.