Search code examples
regexvisual-studio-codecode-snippetsvscode-snippets

Upper camel case to lower camel case as VS Code snippet


I'm trying to create the following line as a snippet for VS Code:

MyFooVariable mytype `json:"myFooVariable"`

So I have the following snippet base

"Struct member declaration with json decorator": {
    "prefix": "json",
    "body": [
        "${1} ${2} `json:\"${1}\"`"
    ],
    "description": "Add suffix for json Marshaller"
}

On the second usage of ${1} I want to replace the upper camel case by lower camel case. I guess I should use regex to make a substitution but as soon as I'm trying to do anything with regex my brain just runs away.

Could you help me with that?

I know I should show you what I attempted but believe me, it's irrelevant.


Solution

  • You want to turn the first character of the input word to lower case. So, you may use a simple ^(.) regex to find that first char and capture it into Group 1 and then use ${1:/downcase} to replace with a lowercase version of that character:

    "body": [
        "${1} ${2} `json:\"${1/^(.)/${1:/downcase}/}\"`"
    ],
    

    This is a "rough" demo of how it works.