繁体   English   中英

删除文件名的扩展名并使用正则表达式 vscode 片段将 camelCase 转换为蛇形大小写?

[英]Remove the extension of filename and convert camelCase to snake case using regex vscode snippets?

我需要在同一结构上创建许多文件。 导出的模块和文件名有一些关系。 我必须转换。 示例输入和输出。

startNewGame.ts => start-new-game
gameOver.ts => game-over
ALongNameForAFile.ts=> a-long-name-for-file
short.ts => short

我目前的正则表达式是

${TM_FILENAME/([A-Z])/-${1:/downcase}/g}

现在我只能删除这么小的更改大写字母并添加- 有两个问题

  • 我无法删除.ts
  • 有额外的-在开始。

注意:我在 vscode 片段中使用它

您即将删除文件扩展名:改用TM_FILENAME_BASE 请参阅vscode 片段变量

"filename change": {
  "prefix": "_co",
  "body": [
    "${TM_FILENAME_BASE/(^[A-Z])|([A-Z])/${2:+-}${2:/downcase}${1:/downcase}/g}",
  ],
  "description": ""
},

由于前导-仅在开头有大写字母时发生,我发现单独处理这种情况最容易。 所以正则表达式现在是:

(^[AZ])|([AZ]) // 顺序很重要。

${2:+-}是一个条件,只有在有捕获组 2 时才添加-

您可以使用此代码段:

 const arr = ['startNewGame.ts', 'gameOver.ts', 'ALongNameForAFile.ts', 'short.ts']; arr.forEach(s => { console.log( s.replace(/(??^)(,=[AZ])/g. '-').replace(/\,\w+$/. '');toLowerCase() ); });

以下是解决此问题的步骤:

  • .replace(/(??^)(,=[AZ])/g, '-') : 在大写字母之前插入-
  • .replace(/\.\w+$/, '') : 移除扩展部分
  • .toLowerCase() :小写结果字符串

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM