Vim - escaping quotes

This Vim regex escapes (by doubling) every double-quote on a line except the first one, last one, or any that are already doubled:

:s/\v(^[^"]*)@<!"@<!""@!([^"]*$)@!/""/g

Sometimes I kind of understand that old humorous quote: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. But regexes are still pretty darn useful. I can't imagine a good replacement for them that wouldn't have all the same problems with escaping and magic characters and whatnot, without the replacement being so verbose that no one would ever use them.

2 Comments

http://gravatar.com/avatar/7b75551e38350bea13d6e40294ebc40e.jpg?d=identicon
Grant says:

Ok, my head exploded. I like and use regexes, but I guess only relatively "simple" ones. Even after reading the vim manual for the explanation of @<! I couldn't grok it.

Oct 17, 2008 08:16 AM PDT
http://gravatar.com/avatar/4d84ec3981443dfd9c287e845b60d2ce.jpg?d=identicon
Brian says:

(^[^"]*)" would match if you can start at the beginning of a string and match up to a quote without hitting any other quotes, i.e. it matches the first quote. Putting a @<! in there negates it, so that means it doesn't match the first quote. Same with "([^"]*$), which would match the last quote, which we also negate. The two extra other clauses, "@<! and "@!, just make sure that if we're going to double a quote, we shouldn't already have another quote on either side of it. All of those assertions are zero-width, so the whole pattern only matches one character.

Oct 17, 2008 09:33 AM PDT

Speak Your Mind

Preview

Commenting Help

Email / Avatar

  • Supply your email address and your Gravatar will be used.
  • I will never email you and your address won't be published.

No HTML allowed!

All HTML is auto-escaped. Use Markdown. Examples:

  • *emphasis* = emphasis
  • **strong** = strong
  • [link](http://foo.bar) = <a href="http://foo.bar">link</a>
  • `code in backticks` = code in backticks
  •     code indented 4 spaces =
    code indented four spaces
  • > Angle-brace quoted text =
    Angle-brace quoted text