How to change lower case to upper using regular expressions in Visual Studio Code

Viewed 19650

I'm using Visual Studio Code 1.14.2, and I'm trying to change name of variables to camelCase eg. set_nominal_wavelength to setNominalWavelength.

Regular expression: _([a-z])

Replace: \U$1\E

does not work. Any idea how to achieve it?

3 Answers

In the 1.47 Insiders Build support for the replace case modifiers (\L, \l, \U, \u) has been added to vscode. And so should be in the 1.47 stable release).

So simply doing your find: _([a-z])

and replace with \u$1 (since you only want to capitalize the first letter) works nicely in the Insiders Build now.

case modifier demo

Works in both the Find Widget and the Search Panel.


Older answer:

In October 2017 snippet variable transforms were added to vscode, see September 2017 release notes, snippet transforms.

As of then you could do this rather easily but you have to set up a simple keybinding:

{
  "key": "alt+-",
  "command": "editor.action.insertSnippet",
  "args": {
    "snippet": "${TM_SELECTED_TEXT/_([a-z])/${1:/capitalize}/g}"
  }
}
  1. Enter _([a-z]) into your find panel,
  2. Ctrl-Shift-L to select all matches, and
  3. Trigger your chosen keybinding from the above example.

No focus changes necessary.

demo of camelCase snippet transform


Unfortunately, no movement on the issue cited by Wiktor case conversions in replace as of June, 2019.

There is a workaround:

  1. Open Replace dialog and enter regex: _([a-z])
  2. Then move focus to the editor area and press Ctrl+F2 ("Change All Occurrences")
  3. Then change case of selection (Ctrl+P >upper)
  4. Then press Left Arrow key and press Delete key
Related