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

Cannot join two regex into one to produce a code snippet to use in VSCode


I am struggling with regular expressions and how to use them in snippets in VSCode and I could really use some help (I am a beginner in that area). I have two regexp:

  • the first one is here to remove the extension from a file path: (.*)\.[^.]+$
  • the second one would output all the occurrences of a backlash in the file path: /(\\)/g

I would like to group them into one regex to use in a user code snippet (html) in VSCode.

From the following input: C:\folder0\myhtml.html I would like to get the following output from the code snippet using transformations: C:/folder0/myhtml (backlashes are replaced with forward ones and the extension is removed).

I know how to write snippets that do it independently:

${TM_FILEPATH/(.*)\\..+$/$1/} would produce C:\folder0\myhtml

${TM_FILEPATH/(\\\\)/\\//g} would produce C:/folder0/myhtml.html

TM_FILEPATH being C:\folder0\myhtml.html in my example. But I cannot combine them.

I have first tried to combine the regex in https://regex101.com/ like this: (\\)(.*)\.[^.]+$ but the result is not what I expect.


Solution

  • In your case you can make it much simpler by using other variables (see snippet variables documentation).

    "${TM_DIRECTORY/(\\\\)/\\//g}/$TM_FILENAME_BASE"

    TM_DIRECTORY gets the full path up to the fileName. C:\folder0 in your example.
    $TM_FILENAME_BASE gets the fileName without the extension. myhtml in your example.

    So all you really need to do is swap those backslashes with forward slashes with the transform: ${TM_DIRECTORY/(\\\\)/\\//g} and concatenate the parts.