TL;DR show me a general vscode snippet to transform "/home/me/projects/project/src/Commands/Interfaces/Whatever" to "Commands\Interfaces\Whatever"
Hi all, I'm using Vscode and trying to figure out a simple transform of the file directory to insert the PHP namespace. So far i could not figure out a simple, general solution to this seemingly mundane problem:
- Is there a way to transform PART of the TM_DIRECTORY variable in a snippet, so that every forward slash becomes a backward slash?
This seems so trivial at first, right? start from
${TM_DIRECTORY/\\//\\\\/}
Then buid up from there. Problem is, I want to catch only part of the filename, THEN transform slashes on the catched group, without resorting to a fixed/maximum number of filename components (in that case, there is an ugly, lengthy solution)
Is the following in the right direction? If so, what replacement string results in group $1 but with slashes reverted?
${TM_DIRECTORY/.*\\/src(\\/([^\\/] )) $/??????/}
Thanks in advance, an acceptable response is "there is just no way unless you relax your requirements", this is more of a theoretical question on the power of regexes.
Edit:
Kudos to @WiktorStribiżew who found the simplest solution, after I posted the question I came up with a far more complicated expression than his:
${TM_DIRECTORY/(([^\\/] )\\/?(?=.*\\/src\\/))|(\\/src\\/)|((?<=\\/src\\/.*)\\/?([^\\/] ))/${5: \\\\}$5/g}
CodePudding user response:
You can use
"${TM_DIRECTORY/^.*?[\\\\\\/]src[\\\\\\/]|([\\\\\\/])/${1: \\\\}/g}"
See the regex demo (there is an extra \
at the start of the resulting string as there is no way to introduce the conditional replacement pattern as in VS Code).
Details:
^
- start of string.*?
- any zero or more chars other than line break chars, as few as possible[\\\/]
-/
or\
charsrc
- the directory name up to which you need to remove the subdirs[\\\/]
- a/
or\
char|
- or([\\\/])
- Group 1: a/
or\
char.
The ${1: \\}
replacement means we replace with \
only when Group 1 match occurs.
Note the backslashes need doubling, and g
at the end replaces all occurrences.