Search code examples
regexvisual-studio-codevscode-snippets

VSCode chaining regex transforms in a snippet


I'm trying to transform a filename automatically in VSCode in two ways. Let's say I have test-file-name.md, I want to end up with Test File Name in my document. Right now I can do both part of the transform separately but I'm struggling to find how to combine them.

  1. To remove all the - and replace them with a space I do this: ${TM_FILENAME_BASE/[-]/ /g}
  2. And for capitalizing the first letter of each word I do: ${TM_FILENAME_BASE/(\b[a-z])/${1:/upcase}/g} (the \b is probably useless in this case I guess)

I've tried multiples way of writing them together but I can't find a way to have them one after the other.


Solution

  • Try this:

    "body": "${TM_FILENAME_BASE/([^-]+)(-*)/${1:/capitalize}${2:+ }/g}"

    Because of the g flag it will get all the occurrences and do each transform of the two capture groups multiple time. In your test case (test-)(file-)(name) that would be three times. It should work for any number of hyphenated words.

    ([^-]+) everything up to a hyphen.

    ${1:/capitalize} capitalize capture group 1.

    ${2:+ } means if there is a 2nd capture group, the (-*), add a space. I added this because at the end there is no hyphen - and thus there will be no 2nd capture group and thus no extra space should be added at the end.