0

Was reading VS Code snippet with multiple transforms and I tried very hard, but was unable to parse how it's being done.

I have a requirement to use ${TM_FILEPATH} and snip out everything preceding a certain point and replace all \ with /.

For both paths of /path/to/lib/file.c and C:\path\to\lib\file.c, I need the results to be /lib/file.c

I have the first part done for my use case:

${TM_FILEPATH/.*lib//}

I can't seem to do the second, though. I've tried:

 ${TM_FILEPATH/\\/\//g}

And I need to do both. If someone answers this, could they also break it down so I can understand what's happening? I'd like to learn how to do these without having to keep asking.

1
  • the linked question does not do multiple transforms, it does multiple matches of the regex (g) and cleverly use the matched groups to apply different modifications on each matched group
    – rioV8
    Commented Aug 4, 2021 at 4:54

2 Answers 2

0

I updated the previous answer so it works much better now.

"PS3": {
  "prefix": "ps3",
  "body": [
    "${TM_FILEPATH/.+?(?=[\\/\\\\]lib)|([\\/\\\\])/${1:+/}/g}",
  ]
}

.+? match everything before what we want. Must do this otherwise unmatched input will "pass through" and not be transformed or eliminated.

(?=[\\/\\\\]lib) a positive lookahead is not part of the match

[\\/\\\\] match either a \ or an / Those characters must be double-escaped in a snippet.

${1:+/} in the replacement - if there was a \ or / matched, replace with a /

-1

You can use the extension HyperSnips

save this snippet in the all.hsnips file in the correct directory

snippet filePart "File Part"
`` rv = path.replace(new RegExp('.*?/path/to/'), '/'); ``
endsnippet

PS. Hypersnips does not work in .txt files

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.