'Renaming namespaces on C# according to the last folder in the file path

I am trying to create a snippet that names a namespace in C# using the name of the last directory in the file path, but it returns everything that comes before it instead.

Here is a demo of the regex, The VSCode snippet, with the replacement values looks like this:

${1:${TM_DIRECTORY/(?<=[\\/\\\\])([a-zA-Z\\-_]+$)/${2:/pascalcase}/}}

because of VS Code quirks and special options.
The output is always the first group, but in the end I am calling the second one. What is causing this?



Solution 1:[1]

You have at least a couple of issues.

First, the first part of the path is being "returned" because you don't actually match it. A lookbehind doesn't include that text as part of the match, as you can see in your demo link.

So unmatched text will not be transformed at all in the snippet, it will just appear where it was.

So you want to match that part of the path even though you will not use it ultimately.

Perhaps you want this regex: (.*[\\/\\\\])([-\w]+$) note no lookbehind

See regex demo

and then:

${1:${TM_DIRECTORY/(.*[\\/\\\\])([-\\w]+$)/${2:/pascalcase}/}}"

Note that it is capture group 2 that is being pascal-cased and that capture group 1 (everything before and including the final path separator) is not used, so it is effectively removed - i.e., it is not in the replacement.

Note the backslashes are doubled because the pattern is passed as a string literal, and / chars must be escaped because the string literal contains a "stringified" regex literal.

\\\\ is escaping each backslash once, it is \\ and another \\ to result in \\ after it is de-stringified. The backslash still operates as an escape character in the [], so if you want a literal \ it must be escaped. And in order to end up with two backslashes in a row like \\, each backslash must itself be escaped in a vscode snippet string.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1