gran_profaci
gran_profaci

Reputation: 8473

Basic Vim - Search and Replace text bounded by specific characters

Say I wanted to replace :

"Christoph Waltz" = "That's a Bingo";
"Gary Coleman" = "What are you talking about, dear Willis?";

to just have :

"Christoph Waltz"
"Gary Coleman"

i.e. I want to remove all the characters including and after the = and the ;

I thought the regex for finding the pattern would be \=.*?\;. In vim, I tried :

:%s/\=.*?\;$//g

but it gave me an Invalid Command error and Nothing after \=. How do I remove the above text? Apologies, but I'm new to this.

Upvotes: 0

Views: 95

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172768

Vim's regular expression dialect is different; its escaping is optimized for text searches. See :help perl-patterns for a comparison with Perl regular expressions. As @EvergreenTree has noted, you can influence the escaping behavior with special atoms; cp. :help /\v.

For your example, the non-greedy match is .\{-}, not .*?, and, as mentioned, you mustn't escape several literal characters:

:%s/ =.\{-};$//

(The /g flag is superfluous, too; there can be only one match anchored to the end via $.)

Upvotes: 1

EvergreenTree
EvergreenTree

Reputation: 2068

This is because of vim's weird handling of regexes by default. Instead of \= interpreting as a literal =, it interprets it as a special regex character. To make vim's regex system work more normally, you can prefix it with \v, which is "very magic" mode. This should do the trick:

%s/\v\=.*\;$//g

I won't explain how vim enterprets every single character in very magic mode here, but you can read about it in this help topic:

:help /magic

Upvotes: 0

Related Questions