更新:键绑定版本:
VScode 在 v1.53 中添加了editor.action.transformToSnakecase
,因此可以更轻松地完成请求的操作,而无需找出必要的正则表达式来使其工作,如上一个答案所示。并且因为有些人可能会在寻找蛇盒(snake-case)信息时发现这个问题。
然而,我现在展示的不是片段。您只需键入文本,然后触发键绑定。键绑定本身从多命令扩展中触发宏扩展命令。在keybindings.json
:
{
"key": "alt+3", // whatever keybinding you wish
"command": "extension.multiCommand.execute",
"args": {
"sequence": [
"cursorWordLeftSelect", // select word you just typed
"editor.action.transformToSnakecase",
"editor.action.transformToUppercase",
// "cursorLineEnd" // if you want this
]
},
"when": "editorTextFocus && !editorHasSelection"
},
按键绑定版本演示:

片段版本:
"camelCaseModify": {
"prefix": "test",
"body": [
// first inefficient try, works for up to three words
// "${1} -> ${1/^([a-z]*)([A-Z])([a-z]+)*([A-Z])*([a-z]+)*/${1:/upcase}_$2${3:/upcase}${4:+_}$4${5:/upcase}/g}"
"${1} -> ${1/([a-z]*)(([A-Z])+([a-z]+))?/${1:/upcase}${2:+_}$3${4:/upcase}/g}",
// here is an especially gnarly version to handle edge cases like 'thisISABCTest' and trailing _'s
"${1} -> ${1/([a-z]+)(?=[A-Z])|([A-Z])(?=[A-Z])|([A-Z][a-z]+)(?=$)|([A-Z][a-z]+)|([a-z]+)(?=$)/${1:/upcase}${1:+_}$2${2:+_}${3:/upcase}${4:/upcase}${4:+_}${5:/upcase}/g}"
],
"description": "underscore separators"
},
这适用于任何数量的驼峰式单词,从一到无穷大......
意思是“ ${2:+_}
如果有一个捕获组 2 则附加一个下划线”。如果没有第二个单词/捕获组,那么组 3 和 4 无论如何都会为空,因为它们在捕获组 2 中。捕获组 2 始终是下一个单词(以一个大写字母开头,后跟至少一个小写字母)。
例如,使用changeNetworkStatus
:
Match 1
Full match 0-13 `changeNetwork`
Group 1. 0-6 `change`
Group 2. 6-13 `Network`
Group 3. 6-7 `N`
Group 4. 7-13 `etwork`
Match 2
Full match 13-19 `Status`
Group 1. 13-13 ``
Group 2. 13-19 `Status`
Group 3. 13-14 `S`
Group 4. 14-19 `tatus`
Match 3
Full match 19-19 ``
Group 1. 19-19 ``
样本输出:
abcd -> ABCD
twoFish -> TWO_FISH
threeFishMore -> THREE_FISH_MORE
fourFishOneMore -> FOUR_FISH_ONE_MORE
fiveFishTwoMoreFish -> FIVE_FISH_TWO_MORE_FISH
sixFishEelsSnakesDogsCatsMiceRatsClocksRocks -> SIX_FISH_EELS_SNAKES_DOGS_CATS_MICE_RATS_CLOCKS_ROCKS
使用regex101.com确实有助于可视化正在发生的事情!