Warm tip: This article is reproduced from stackoverflow.com, please click
regex visual-studio-code vscode-snippets

Can I exclude Positive Lookaheads and Lookbehinds within a snippet in vscode?

发布于 2020-03-27 10:29:24

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/...
Questioner
kbDS
Viewed
129
Wiktor Stribiżew 2019-07-03 23:34

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 [^\\/]+.