reectrix
reectrix

Reputation: 8629

How do you replace the content of html tags in vim?

For instance, if I want to replace <person>Nancy</person> with <person>Henry</person> for all occurrences of <person>*</person> in vim?

Currently, I have:

%s:/'<person>*<\/person>/<person>Henry<\/person>

But obviously, this is wrong.

Upvotes: 1

Views: 1693

Answers (2)

romainl
romainl

Reputation: 196546

:%s/\v(<person>).\{-}(<\/person>)/\1Henry\2/g

does what you want but yeah, what Ingo said.

  • \v means "very magic": it's a convenient way to avoid backslashitis.

  • (something) (or \(something\) without the \v modifier) is a sub-expression, you can have up to nine of them in your search pattern and reuse those capture groups with \1...\9 in your replacement pattern or even later in your search pattern. \0 represents the whole match. Here, the opening tag is referenced as \1 and the closing tag as \2.

Upvotes: 1

Ingo Karkat
Ingo Karkat

Reputation: 172550

For a single substitution, Vim offers the handy cit (change inner tag) command.

For a global substitution, the answer depends on how well-structured your tag (soup) is. HTML / XML have a quite flexible syntax, so you can express the same content in various ways, and it becomes increasingly harder to construct a regular expression that matches them all. (Attempting to catch all cases is futile; see this famous answer.)

Upvotes: 4

Related Questions