1

I am having issues excluding parts of a string in a VSCode Snippet. Essentially, what I want is a specific piece of a path but I am unable to get the regex to exclude what I need excluded.

I have recently asked a question about something similar which you can find here: Is there a way to trim a TM_FILENAME beyond using TM_FILENAME_BASE?

As you can see, I am getting mainly tripped up by how the snippets work within vscode and not so much the regular expressions themselves

${TM_FILEPATH/(?<=area)(.+)(?=state)/${1:/pascalcase}/}

Given a file path that looks like abc/123/area/my-folder/state/...

Expected:

/MyFolder/

Actual:

abc/123/areaMyFolderstate/...
Emma
  • 27,428
  • 11
  • 44
  • 69
kbDS
  • 35
  • 2

3 Answers3

1

You need to match the whole string to achieve that:

"${TM_FILEPATH/.*area(\\/.*?\\/)state.*/${1:/pascalcase}/}"

See the regex demo

Details

  • .* - any 0+ chars other than line break chars, as many as possible
  • area - a word -(\\/.*?\\/) - Group 1: /, any 0+ chars other than line break chars, as few as possible, and a / -state.* - state substring and the rest of the line.

NOTE: If there must be no other subparts between area and state, replace .*? with [^\\/]* or even [^\\/]+.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

The expected output seems to be different with part of a string in the input. If that'd be desired the expression might be pretty complicated, such as:

(?:[\s\S].*?)(?<=area\/)([^-])([^-]*)(-)([^\/])([^\/]*).*

and a replacement of something similar to /\U$1\E$2$3\U$4\E$5/, if available.

Demo 1

If there would be other operations, now I'm guessing maybe the pascalcase would do something, this simple expression might simply work here:

.*area(\\/.*?\\/).*

and the desired data is in this capturing group $1:

(\\/.*?\\/)

Demo 2

Emma
  • 27,428
  • 11
  • 44
  • 69
0

Building on my answer you linked to in your question, remember that lookarounds are "zero-length assertions" and "do not consume characters in the string". See lookarounds are zero-length assertions:

Lookahead and lookbehind, collectively called "lookaround", are zero-length assertions just like the start and end of line, and start and end of word anchors explained earlier in this tutorial. The difference is that lookaround actually matches characters, but then gives up the match, returning only the result: match or no match. That is why they are called "assertions". They do not consume characters in the string, but only assert whether a match is possible or not.

So in your snippet transform: /(?<=area)(.+)(?=state)/ the lookaround portions are not actually consumed and so are simply passed through. Vscode treats them, as it should, as not actually being within the "part to be transformed" segment at all.

That is why lookarounds are not excluded from your transform.

Mark
  • 143,421
  • 24
  • 428
  • 436