How to change lower case to upper using regular expressions in Visual Studio Code
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?
Solution 1:
There is a workaround:
- Open Replace dialog and enter regex:
_([a-z])
- Then move focus to the editor area and press Ctrl+F2 ("Change All Occurrences")
- Then change case of selection (Ctrl+P >upper)
- Then press Left Arrow key and press Delete key
Solution 2:
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.
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}"
}
}
- Enter
_([a-z])
into your find panel, - Ctrl-Shift-L to select all matches, and
- Trigger your chosen keybinding from the above example.
No focus changes necessary.
Unfortunately, no movement on the issue cited by Wiktor case conversions in replace as of June, 2019.
Solution 3:
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.