DEV Community

Rach Smith
Rach Smith

Posted on • Originally published at rachsmith.com on

Using regex with make find-and-replace in VS Code

The context for how and why is too niche for me to go in to here, but I had a bunch of files where I needed to change all instances of this:

'FileClient:1643853467530'

to this:

'PenVersionFileClient:{"cpid":"1643853467530"}'

Except for each instance, the id value (the number) was different.

I wanted to keep the number in there, but change the text that wraps it.

Because I needed to replace text on either side of the number, a simple find-and-replace term wasn't going to work. I needed regex.

To turn on search using regex, you want to make sure this option is selected:

A screenshot of VS Code's search sidebar with "Use Regular Expression" selected

To replace the text on either side of text, you want a regular expression that follows this pattern:

/BEFORE_TEXT(.+?)AFTER_TEXT/

where BEFORE_TEXT and AFTER_TEXT match the text on the left and the right of the text you want to wrap-replace.

Then, in the Replace input of the Search UI, you add a $1 to wherever you want the original text to go.

NEW_BEFORE_TEXT$1NEW_AFTER_TEXT

For my case above, I used this:

Search : 'FileClient:(.+?)'

Replace : 'PenVersionFileClient:{"cpid":"$1"}'

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay