我想创建一个VS Code片段以创建redux reducer。
我想要一个带有占位符的代码段,期望使用camelCase,然后将匹配的占位符转换为SCREAMING_SNAKE_CASE。
这是我尝试的代码段,不起作用:
"test": {
"prefix": "test",
"body": "${1} -> ${1/([a-zA-Z])(?=[A-Z])/${1:/upcase}_/g}"
},
哪个会产生不希望的结果:
changeNetworkStatus -> changE_NetworK_Status
test
(代码段名称)键入changeNetworkStatus
会导致:
changeNetworkStatus -> changeNetworkStatus
点击选项卡可获得以下结果:
changeNetworkStatus -> CHANGE_NETWORK_STATUS
如何更改代码段以获得所需的结果?
答案 0 :(得分:8)
"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}"
],
"description": "underscore separators"
},
这适用于任何数量的驼峰词,从一个到无穷大...
${2:+_}
的意思是“如果有捕获组2,则添加下划线”。如果没有第二个单词/捕获组,则第3组和第4组将始终为空,因为它们在捕获组2内。捕获组2始终是下一个Word(以一个大写字母开头,后跟至少一个小写字母) )。
例如,使用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确实有助于可视化正在发生的事情!