Insert matched pattern

4.6
(220)

We have written numerous tips about pattern matching, mostly because it’s such a valuable skill to develop. A few popular ones include Repeat last substitution, Stay in search mode, and Count occurrences.

But there also just seems to be so much to learn about this corner of Vim. Here’s a trick I learned recently: An ampersand, & , in your replacement pattern will insert the matched pattern into the replacement text. This could be useful in a lot of places, such as surrounding text with something. (Although you are using Surround.vim, right?)

Take a look at the gif at the bottom of this post. In the demo, I use this tip to match URLs and replace them with markdown syntax. The substitution looks like so:

%s/https\?.*/[&](&)/g

Here’s what this does:

  • % – set the range to the entire file
  • s – substitution
  • /https\?.*/ – regex to match http or https and anything else after it
  • [&](&)– The & is the magic here and inserts the matched text. In this case, the URL. The rest of the characters are interpreted literally, giving us the linked URL in the resulting markdown.
  • /g changes all the matches on a line

Note that not all Markdown flavors support this textless link format. But regardless, the point is to demonstrate using the matched pattern inside your substitution. (As an aside, if you write a lot of Markdown, you’re going to want vim-markdown-preview.)

This tip goes well together with the use of uppercase and lowercase escape characters for changing case. Now onto the demo video:

How useful was this tip?

Average rating 4.6 / 5. Vote count: 220

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

90 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

Leave a reply

Your email address will not be published. Required fields are marked *