I'm writing a snippet in VS Code using variable transforms. I want to replace a pattern that occurs in some text (in this case text copied on the clipboard) with a variable that inserts the name of the file without extensions (for example: CurrentFileNameWithoutExtensions). What happens is the pattern gets replaced with the variable name as a string, and not the value of the variable.
Here's the snippet:
"${CLIPBOARD/pattern/$TM_FILENAME_BASE/}"
The output is: "pattern" becomes "$TM_FILENAME_BASE".
The correct output would be: "pattern" becomes "CurrentFileNameWithoutExtensions".
A possible solution to this could be outputting all the clipboard text before the pattern, then the variable, and finally all the clipboard text after the pattern. How would this be done?
Example clipboard text:
Text that is before pattern in clipboard.
pattern
Text that is after pattern in clipboard.
The snippet could capture all text until the pattern and output it:
Text that is before pattern in clipboard.
Then it would output the variable $TM_FILENAME_BASE:
CurrentFileNameWithoutExtensions
Finally it would output the text after the pattern:
Text that is after pattern in clipboard.
The output would look like this put together:
Text that is before pattern in clipboard.
CurrentFileNameWithoutExtensions
Text that is after pattern in clipboard.
2 Answers 2
If there is always a matching pattern, then this works:
"pattern": {
"prefix": "_pt",
"body": [
"${CLIPBOARD/(.*[\r\n]*)((pattern)([\r\n]*))(.*)/1ドル/}$TM_FILENAME_BASE${CLIPBOARD/(.*[\r\n]*)((pattern)([\r\n]*))(.*)/4ドル5ドル/}"
],
"description": "clipboard pattern"
}
This handles any number of newlines as in
first text
pattern
second text
or
first text
pattern
second text
or
first textpatternsecond text
See regex101 demo
Of course, as rioV8 points out, if pattern also matches in the text somewhere in addition to the middle that is a problem.
Comments
Capture the different parts in groups and only output the group you want
It works also if pattern is not part of the CLIPBOARD
"${CLIPBOARD/^((.*?)(pattern.*)|(.*))$/2ドル4ドル/}$TM_FILENAME_BASE${CLIPBOARD/^((.*?pattern)(.*)|(.*))$/3ドル/}"
7 Comments
"${CLIPBOARD/(.*?)(pattern.*)/1ドル/}${TM_FILENAME_BASE}${CLIPBOARD/(.*?pattern)(.*)/2ドル/}"pattern, I have modified it so it also works (tested) if pattern is not in CLIPBOARD, for explanation read up on regular expressionspattern, modify the example to match a real case, 3 times the same text messes with the case that you want the middle one replaced
patternorreplacementparts of a transform (other than the case modifiers and conditionals). There may be an extension that can do that though.