3

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)*
}
Mark
  • 143,421
  • 24
  • 428
  • 436
micomec
  • 71
  • 8
  • I'm not sure about visual studio custom snippets, but in javascript something like this would work: `('formatted_like_this').split('_').map((el)=>el.charAt(0).toUpperCase() + el.slice(1)).join('')`. I'm not sure if it helps, but maybe you can write something similar in visual studio? – Berci Dec 02 '19 at 19:18
  • 1
    @Berci Unfortunately I cannot use JavaScript string functions for this purpose, but thank you for your prompt reply! – micomec Dec 02 '19 at 20:10

1 Answers1

2

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}()",
Mark
  • 143,421
  • 24
  • 428
  • 436
  • 1
    Thank you so much Mark, this worked perfectly! I really appreciate your help. – micomec Dec 02 '19 at 20:34
  • brilliant second option. That definitely further's my understanding of Regex expression reading. Any idea what the Regex would be for [ this_camel_case => thisCamelCase ] (first word begins lcase, all other words begin ucase)? – micomec Dec 03 '19 at 18:38
  • 1
    See my answer here for camelCase: https://stackoverflow.com/questions/48104851/snippet-regex-match-arbitrary-number-of-groups-and-transform-to-camelcase/51228186#51228186 – Mark Dec 03 '19 at 18:56
  • how about if you need to get rid of underscores '_'? – Leland Reardon May 29 '23 at 06:35
  • @LelandReardon You'll have to explain your starting text, the `pascalcase` transform does get rid of the underscores. Do you mean get rid of underscores and do nothing else? – Mark May 29 '23 at 21:11