Reputation: 79735
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?
Upvotes: 12
Views: 6216
Reputation: 42258
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. :)
Upvotes: 18
Reputation: 901
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
Upvotes: 6
Reputation: 12934
This will run your regex on the current file:
:%s/\[.*\]\(.*{\)/\1/g
Upvotes: 0
Reputation: 15735
How about:
:%s#\[.*\]\ze.*{##g
Note that the \ze
item marks the end of the match, so anything that follows is not replaced.
Upvotes: 2