Home > Enterprise >  Renaming namespaces on C# according to the last folder in the file path
Renaming namespaces on C# according to the last folder in the file path

Time:05-12

I am trying to create a snippet for naming namespaces on C# according to the last folder in the file path, but it returns everything that comes before it. I've made a demo of the regex, but what actually is in the snippet is:

${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?

CodePudding user response:

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.

  • Related