Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search/Replace in Vim

I want to delete all occurrences of square brackets that conform to this regex: \[.*\].*{, but I only want to delete the brackets, not what follows - i.e., I want to delete the brackets and what's inside them, only when they are followed by an opening curly brace.

How do I do that with Vim's search/replace?

like image 833
Amir Rachum Avatar asked Apr 28 '11 14:04

Amir Rachum


2 Answers

If you surround the last bit of your regex in parenthesis you can re-use it in your replace:

:%s/\[.*\]\(.*{\)/\1/g

The \1 references the part of the regex in parenthesis.

I like to build my search string before I use it in the search and replace to make sure it is right before I change the document:

/\[.*\]\(.*{\)

This will highlight all the occurrances of what you will replace.
Then run the %s command without a search term to get it to re-use the last search term

:%s//\1/g
like image 177
Sam Brinck Avatar answered Sep 19 '22 12:09

Sam Brinck


You can use \zs and \ze to set the beginning and the end of the match.

:%s/\zs\[.*\]\ze.*{//g should work.

You are telling Vim to replace what is between \zs and \ze by an empty string.

(Note that you need the +syntax option compiled in your Vim binary)

For more information, see :help /\zs or :help pattern

Edit : Actually \zs is not necessary in this case but I leave it for educational purpose. :)

like image 20
Xavier T. Avatar answered Sep 21 '22 12:09

Xavier T.