Search code examples
regexvisual-studio-codecode-snippetsregexp-replacevscode-snippets

vscode snippet transform file name regex


I'm trying to transform file-name.dto.ts to FileName in a snippet.

${TM_FILENAME_BASE/^(.*)([^.*]).*/${1:/pascalcase}$2/}

However, I'm not quite sure how to transform the second capture group or third.

If we don't wrap with a parenthesis, does it mean we don't capture?

  export class ${TM_FILENAME_BASE/^(.)([^.]*).*/${1:/upcase}$2/}Input {$2},
  export class ${TM_FILENAME_BASE/^(.*).*/${1:/pascalcase}$2/}Output {},

Solution

  • For the first line (the Input line), try this:

    "export class ${TM_FILENAME_BASE/^([^-]*)-([^.]*).*/${1:/pascalcase}${2:/pascalcase}/}Input {$2},"

    1. ${TM_FILENAME_BASE} alone gets you tofile-name.dto

    2. Capture group 1 ^([^-]*) gets you the part before the first -

    3. Match the - but you will ignore it in the output so it doesn't need to be in a capture group.

    4. Capture group 2 ([^.]*) after the - until the first .

    5. The rest .* will match .dto which again will be ignored so it doesn't need to be a capture group, but must be matched - you will effectively replace it with nothing.

    Replacing with the transform: ${1:/pascalcase}${2:/pascalcase} so the first letter of both capture groups will be capitalized, the rest lower case.

    On the Output line, if you are looking for this result:

    export class FileNameOutput {}

    use

    "export class ${TM_FILENAME_BASE/^([^-]*)-([^.]*).*/${1:/pascalcase}${2:/pascalcase}/}Output {},"


    Just in case you don't realize it, in your code:

    export class ${TM_FILENAME_BASE/^(.)([^.]*).*/${1:/upcase}$2/}Input {$2},

    that last {$2} is NOT referring to any capture group - it is outside any transform. It is only referring to a tabstop - where your cursor will go. Let me know if it is your intention that that final {$2} actually be a transformed capture group.