the_gesslar
the_gesslar

Reputation: 389

VS Code Snippets Multiple Transforms on a single variable

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.

Upvotes: 0

Views: 489

Answers (2)

Mark
Mark

Reputation: 182781

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 /

Upvotes: 0

rioV8
rioV8

Reputation: 28838

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

Upvotes: -1

Related Questions