0

If I search for patterns in vim with regex, then want to insert something without changing what the regex matched, what do I do? For example, in a file with

foo123
bar4567

12zw231xy

I want to insert a newline between every non-digit followed by a digit, resulting in a file like this:

foo
123
bar
4567

12zw
231xy
0
3
:%s/\(\D\)\(\d\)/\1\r\2/g
  • \(\) are capture groups. What is captured in them is reproduced by \1 and \2.

  • \D is a non-digit, \d is a digit.

  • \r becomes a newline character in Vim.

This gets simplified with magic mode regex, enabled with \v:

:%s/\v(\D)(\d)/\1\r\2/g
2
  • 1
    The \zs and \ze anchors are really useful to avoid capturing groups in many cases such as this one. You can use them here to make a zero-width match in between the two characters: :%s/\D\zs\ze\d/\r/g. Or you can use only one of them, in which case you can use & on the right to repeat the whole match: :%s/\D\ze\d/&\r/g or conversely :%s/\D\zs\d/\r&/g. Without the capture groups, you don't need to resort to the \v mode anymore, all backslashes are before letters (so wouldn't change under "verymagic").
    – filbranden
    Dec 22 '20 at 8:48
  • 1
    @filbranden Very nice, thanks for teaching us something new!
    – Quasímodo
    Dec 22 '20 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.