VSCode 要转换为蛇形案例的用户代码段

VSCode user snippet to convert to snake case

是的,我知道这是当前的功能。我要找朋友 (Azure Data Studio)。

我需要一个用户代码段,将 Camel Case 或 Pascal Case(突出显示)字符串转换为小蛇形。我在这里修改了 this answer 这让我很接近,但它无法处理一系列大写字母,例如HTML.

"snake":{
    "prefix": "snake",
    "body": "${TM_SELECTED_TEXT/(^[A-Z][a-z]*|[a-z])([A-Z])?/${1:/downcase}${2:+_}${2:/downcase}/g}"
}

理想情况下我可以获得像

这样的结果

Converts a string to snake case.

  • Use String.prototype.match() to break the string into words using an appropriate regexp.
  • Use Array.prototype.map(), Array.prototype.slice(), Array.prototype.join() and String.prototype.toLowerCase() to combine them, adding _ as a separator.
const toSnakeCase = str =>
  str &&
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(x => x.toLowerCase())
    .join('_');


toSnakeCase('camelCase'); // 'camel_case'
toSnakeCase('some text'); // 'some_text'
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'
toSnakeCase('AllThe-small Things'); // 'all_the_small_things'
toKebabCase('IAmEditingSomeXMLAndHTML');

来自 30 seconds of code: convert to snake_case

试试这个(我从你的第二个 link 转换了正则表达式):

"snake": {
  "prefix": "snake",
  "body": "${TM_SELECTED_TEXT/([A-Z]{2,})(?=[A-Z][a-z]+[0-9]*|$)|([A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+)([- _])?/${1:/downcase}${2:/downcase}${2:+_}/gm}"
},

现在,它在末尾添加了一个额外的 _,您可以将其退格或将其放入为您执行此操作的宏中。这里使用 multi-command:

{
  "key": "alt+enter",             whatever keybinding you want
  "command": "extension.multiCommand.execute",
  "args": {
    "sequence": [
      {
        "command": "editor.action.insertSnippet",
        "args": {
          "snippet": "${TM_SELECTED_TEXT/([A-Z]{2,})(?=[A-Z][a-z]+[0-9]*|$)|([A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+)([- _])?/${1:/downcase}${2:/downcase}_/gm}"
        },
      },
      "deleteLeft"
    ]
  },
  "when": "editorTextFocus && editorHasSelection"
}

此版本不包含尾随 _

感谢您为我指出正确的方向。

"snake": {
        "prefix": "snake",
        "body": "${TM_SELECTED_TEXT/([A-Z][a-z]+$)|([A-Z][a-z]+)/${1:/downcase}${2:/downcase}${2:+_}/g}"
    }

示例 VS 代码片段

"pyp": {
        "prefix": "Generate full Property",
        "body": [
            "@property",
            "def ${1:name}(self) -> ${2:str}:",
            "    \"\"\"Specifies ${1:name}",
            "",
            "        :getter: Gets ${1:name} value.",
            "        :setter: Sets ${1:name} value.",
            "    \"\"\"",
            "    return self._${1/([A-Z][a-z]+$)|([A-Z][a-z]+)/${1:/downcase}${2:/downcase}${2:+_}/g}",
            "",
            "@${1:name}.setter",
            "def ${1:name}(self, value: ${2:str}):",
            "    self._${1/([A-Z][a-z]+$)|([A-Z][a-z]+)/${1:/downcase}${2:/downcase}${2:+_}/g} = value[=11=]"
        ],
        "description": "pyp"
    }

样本 snippet-generator.app