【发布时间】:2022-08-19 02:36:24
【问题描述】:
我的文件名:company-news-model.js
我希望它变成company_news;
标签: visual-studio-code vscode-snippets
我的文件名:company-news-model.js
我希望它变成company_news;
标签: visual-studio-code vscode-snippets
如果你必须把它放在一个 sn-p 中,试试这个:
"filePath to snake": {
"prefix": "2Snake",
"body": [
"${TM_FILENAME_BASE/-([^-]*)(?=-)|(-.*)$/${1:+_}$1/gm}"
// gm regex flags are both necessary
// just put a ; at the end (before the closing quote) if you want one there
]
}
它适用于任何长度的文件名,如 a-b-c-d.js 等。
使用您的示例文件:company-news-model.js
TM_FILENAME_BASE:company-news-model
-([^-]*)(?=-) :仅匹配 -news,捕获组 1
(-.*)$ :匹配名称的结尾,-model 在第 2 组中,我们不会在替换中使用
请注意,company 永远不会匹配,只要在最终结果中可以接受它,您就不需要匹配,就是这样。
替换变换:
${1:+_} :这意味着如果有一个组 1,插入一个_$1 :插入组 1
所以company 失败,因为它永远不会匹配,然后是_ 和组1。然后因为它是一个全局正则表达式,所以再添加_ 和找到的组1。
请注意,
company-news-model.component.js之类的文件将按照我的预期转换为company_news。
更强大的方法可以转换任何情况下的文件名到 kebab-case - 但这将是一个键绑定而不是一个 sn-p。您将需要扩展名Find and Transform(由我编写)。
进行此键绑定(在您的
keybindings.json中):{ "key": "alt+s", // whatever keybinding you want "command": "findInCurrentFile", "args": { // inserted at the cursor(s), if cursor is not in or against a word "replace": "${fileBasenameNoExtension}", "postCommands": ["editor.action.transformToKebabcase", "cancelSelection"] }, }插入、选择
fileBasenameNoExtension,然后在其上运行命令editor.action.transformToKebabcase。
【讨论】: