Search code examples
regexvisual-studio-codevscode-snippets

How to extract all matches with regex in VSCode snippets and return them in a specific format?


I am trying to create a snippet that extract certain elements on the path to the file. A path may look something like this:

/src/routes/server/[region]/[serverno]/user/[id]/profile

I want the snippet to give the following output:

region, serverno, id

I have tried multiple ways to do it, but it always requires me to specify which element I want, and I cannot make it so that it matches ALL elements.

"${TM_FILEPATH/.*(?<=\\[)(.*?)(?=])(.*?)(?<=\\[)(.*?)(?=]).*/$1, $3/g}"

would produce:

serverno, id

given the example above.

This is a poor attempt at solving this issue, however this only works for the last 2 elements wrapped in [ ].

Is there a way to do this with VSCode snippets or is it necessary to use something else?


Solution

  • try these

    "${TM_FILEPATH/[^\\[]*\\[([^\\]]+)\\][^\\[]*/$1, /g}"
    

    or

    "${TM_FILEPATH/[^\\[]*\\[([^\\]]+)\\][^\\[]*\\[([^\\]]+)\\][^\\[]*\\[([^\\]]+)\\][^\\[]*/$1, $2, $3/}"