Search code examples
jsonregexvisual-studio-codecamelcasingvscode-snippets

VSCode snippet, transform lowercase string delimited by underscores into CamelCase?


I'm writing a custom snippet in VSCode to help me define custom class methods easily. I need to be able to enter a string 'formatted_like_this' and have the regex transform that string in certain places so that it becomes 'FormattedLikeThis'?

The custom snippet to be written in php.json: (see 'NEED HELP WITH REGEX HERE' for the spot where I am struggling)

"New Custom Class Method For Variable": {
    "prefix": "contcmpffv",
    "body": [
        "protected $$1 = null;",
        "public function get${NEED HELP WITH REGEX HERE}()",
        "{",
        "\t$0",
        "}"
    ],
    "description": "Controller Class Method Public Function For Variable"
}

My desired workflow: 1. type contcmpffv 2. press enter when prompted with matching snippet 2. snippet prompt's me for $1

Desired Output (inputting "test_input_string" when prompted for $1):

protected $test_input_string = null;
public function getTestInputString()
{
    *cursor resolves here (due to $0)*
}

Solution

  • Try:

    "body": [
        "protected $$1 = null;",
        "public function get${1/(.*)/${1:/pascalcase}/}()",
        "{",
        "\t$0",
        "}"
    ],
    

    It uses the undocumented pascalcase transform - which has been around for some time. It does all the work for you in this case.

    This is what you could use if there was no pascalcase:

    "public function get${1/([^_]*)_*/${1:/capitalize}/g}()",