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

RegexVisual Studio-Code

Regex Problem Overview


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?

Regex Solutions


Solution 1 - Regex

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

Solution 2 - Regex

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.

Solution 3 - Regex

You may use other tools that support change case operators, like Notepad++, sed, R (gsub with perl=TRUE), but VS Code does not support these operators in the replacement pattern.

See this feature request on GitHub:

> This is cool to have. This is beyond the scope of what is currently supported by javascript. > > We need to come up with our own advanced replace engine to support these cases.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaciej HajView Question on Stackoverflow
Solution 1 - RegexDmitry SokolovView Answer on Stackoverflow
Solution 2 - RegexMarkView Answer on Stackoverflow
Solution 3 - RegexWiktor StribiżewView Answer on Stackoverflow