Regex search/replace while preserving groups
For reference, I’m noting down here how to do a search and replace using regex when the text being replaced/removed is surrounding some text I want to keep. This came up in code with lots of occurrences of higher order functions:
some_function((argument) => { return something; })
Where I wanted to remove the wrapping function, i.e. I wanted to get
(argument) => { return something; }
This regex works nicely
(some_function\()([\W\w]*?)(\))
This creates 3 capturing groups. The first one for whatever you want to remove/change, the second one is the part you want to keep, and the third for whatever is after that you also want to remove/change. The [\w\W]*
part matches all word and non-word characters across newlines and the ?
makes the smallest possible match (without it you might get all the occurrences in a single match). And for the replace part you specify to emit the middle capturing group:
$2
Plus whatever you want to add before or after. I’ve done this in context of VS Code but it will work anywhere with search/replace regex functionality. It’s hard to beat a satisfying regex!
Note: there might be a fancier way of doing this with lookbehinds and lookaheads that I haven’t dug into.