Search code examples
regexvisual-studio-coderegexp-replacevscode-snippets

vscode snippet - multiple regex transformation filepath+filename


after 1 week of searching and try&error I'm creating this question in the hope of someone willing to help me out on this one:

My VsCode Snippet should transform the following:

D:\FolderX\FolderY\src\Folder1\Folder2\Folder3

into:

FOLDER1_FOLDER2_FOLDER3_FILENAMEBASE

Folder3 could be optional

what if come up so far is:

"body": [
    "${TM_DIRECTORY/^.+(src\\\\)(.*)$/${2:/upcase}${3:/upcase}/g}_${TM_FILENAME_BASE/(.*)/${1:/upcase}/}",
],

and the result so far is:

FOLDER1\FODLER2\FOLDER3_FILENAMEBASE

so all I need to do now is change the \ to _ but I want that in one transformation if it's possible..
Anyone have an idea or better solution for my problem?
Thanks alot


Solution

  • You can use

    "body": [
        "${TM_DIRECTORY/^(?:.*\\\\)?src\\\\|([^\\\\]+)|(\\\\)/${1:/upcase}${2:+_}/g}_${TM_FILENAME_BASE/.+/${0:/upcase}/}",
    ],
    

    Details:

    • ^ - start of string
    • (?:.*\\\\)? - an optional sequence of any zero or more chars other than line break chars as many as possible and then
    • src\\\\ - src\ string
    • | - or
    • ([^\\\\]+) - Group 2: one or more chars other than \
    • | - or
    • (\\\\) - Group 3: a \ char.

    The ${1:/upcase}${2:+_} replacement means that Group 1 is always returned uppercased, and if Group 2 matches (a \ char), it is replaced with a _ char.

    The ${TM_FILENAME_BASE/.+/${0:/upcase}/} is simplified as there is a $0 backreference to the whole match, no need to wrap the whole pattern with a capturing group.