Snippet regex: match arbitrary number of groups and transform to CamelCase

让人想犯罪 __ 提交于 2019-11-28 01:47:36

问题


In a Visual Studio Code Snippet I'm writing I want to convert a snake case string to camel case.

From the docs I know that the syntax is

'${' var '/' regex '/' (format | text)+ '/' options '}'

so I've come up with this :

${TM_FILENAME_BASE/([a-z])([a-z]*)_+([a-z])([a-z]*)_+/${1:/upcase}$2${3:/upcase}$4/}

This code however works only for strings with 2 elements (for exemple "carrot_cake") while I would like to process strings with arbitrary number of elements ("blueberry_pie_with_a_cup_of_coffee").

I guess that some kind of recursion is needed in 'regex' and 'format', but I have no idea of what to do.

How does one match arbitrary number of pattern occurrences?


回答1:


To transform an arbitrary number of "_" separated words into CamelCase try:

EDIT: In October, 2018 (but not yet added to snippet grammar documentation as of June, 2019) vscode added the /pascalcase transform, see commit. I have modified the code below to use the /pascalcase transform. It only works for the some_file => SomeFile type of CamelCase though.

"camelCase": {
    "prefix": "_cc",
    "body": [
            // "${TM_FILENAME_BASE/([a-z]*)_+([a-z]*)/${1:/capitalize}${2:/capitalize}/g}"

            "${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/g}"
        ],
        "description": "Transform to camel case"
    },

carrot_cake.txt -> CarrotCake

blueberry_pie_with_a_cup_of_coffee.js -> BlueberryPieWithACupOfCoffee

[I assume CamelCase is the form you want, there are others, such as camelCase.]

For camelCase:

"${TM_FILENAME_BASE/([a-z]*)_*([a-z]*)/$1${2:/capitalize}/g}"

Note that the "g" flag at the end is doing most of that work for you in getting however many matches there are beyond the two explicitly captured.

I left the capture groups as ([a-z]*) as you had them. You may want to use ([A-Za-z0-9]*) for more flexibility.



来源:https://stackoverflow.com/questions/48104851/snippet-regex-match-arbitrary-number-of-groups-and-transform-to-camelcase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!