Smart Find & Replace in code editor

We will use capturing groups !

- /(group)/ : This captures a group and stores it in a base-1 indexed array

-

: This allows to match what has been captured in the nth group

This feature is VERY important.

Example !

Let’s say you’re working on a chat app within which everyone has to type his ID. Your app is very strict on IDs, they must start and end with the same digit.

Each ID follow this scheme : X-PSEUDO-X where X is a digit.

This is how you solve the problem :

What happened ?

We captured the first digit with (\d) , this digit has been put in an array of captured groups.

Then we used -.+- to match any pseudonym bounded by hyphens.

Finally, we used \1 to reuse the first captured digit (which equals 6).

It’s only the peak of the iceberg

Here is the interesting part !

Using $n in a function which accepts regular expressions as parameter allows us to work with captured groups. ( n is the nth captured group)

Example !

How cool ?!?!?! 😍😎

You could work with two groups and use $1 and $2 for instance.

The best is that you can do it in the Find & Replace tool of code editors.

For instance using VSCODE :

I want to truncate the decimal part of each variable.

Done in seconds !

Some tips :

Don’t forget to escape parenthesis and braces

Always try to capture the largest groups so that you don’t have to rewrite too much of a string.

Use \s+ and

+ when dealing with multiple lines in a code editor as the \m flag is rarely supported.

Real use-case

I was working on a JS project which had not been updated to ES6 syntax and one of the things I did was to convert all the functions to their ES6 equivalent.

This is what I wanted :

That’s how I did in VSCODE :

I built my regular expression by hand :