Reference groups in search and replace in Vim

Reading Time: 1 minute

Solution

A group is defined with parentheses and they must be backspaced: \(group_regex\). You can reference groups from the “search” regex into the “replace” regex with \x, where x is the number of the group.

Let’s say you want to add dashes around digits in a text file, from “today is 20 May 2022” to “today is -2–0- May -2–0–2–2-”. You can do it like this:

:%s/\(\d\)/-\1-/g

We transform challenges into digital experiences

Get in touch to let us know what you’re looking for. Our policy includes 14 days risk-free!

Free project consultation