Well, i was strugling with that too, but with all of the responses in this post i was able find the following solution:
"namespace ${RELATIVE_FILEPATH/(\\\\([^\\\\]+)$)|(\\\\)/${3:+.}/g} ;",
This will replace every backslash with a dot and remove the filename. Example: MyFolder\\SubFolder\\MyFile.cs will generate MyFolder.SubFolder
My Full Snippet File:
{
"Default C# Class": {
"prefix": "csclassstart",
"isFileTemplate": true,
"body": [
"using System;",
"",
"namespace ${RELATIVE_FILEPATH/(\\\\([^\\\\]+)$)|(\\\\)/${3:+.}/g} ;",
"",
"public class ${TM_FILENAME_BASE} {",
" $0",
" public ${TM_FILENAME_BASE}(){",
" }",
"}",
""
],
"description": "C# class with dynamic class name and namespace derived from file name directories"
}
}
How this works
Our goals are the following: (1) Remove the \\filename.cs from the RELATIVE_FILEPATH variable; (2) replace the double-backslashes (\\) with dots (.)
First we capture the filename by capturing everithing that matches the following:
- double-backslashes
\\\\
- followed by something that isnt a backslash
([^\\\\]+)
- followed by the end of the string
$
This generates two capture groups
they are: (\\\\([^\\\\]+)$) and ([^\\\\]+) (the second is inside the first)
but we dont realy care about them, we just neet to keep count.
Then we use a OR | to capture a third group, witch is composed exclusively of double-backslashes (\\\\).
Finaly, we replace all captured groups with the following: ${3:+.} witch basically means,
if capture-group 3 is not empty, replace it with a dot (.).
With that, all double-backslashes will be replaced by dots, except the ones in \\filename.cs.
Thats happens because of the OR operator (|), witch will make this sequence will match the first capture-group and skip the third, making it empty and not triggering the replacement.
Because of that, is important to note that the order of the capture-groups is very important for this to wwork