This is a read-only archive!

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.

October 16, 2008 @ 9:52 AM PDT
Cateogory: Programming
Tags: Vim, Regex

2 Comments

Grant
Quoth Grant on October 17, 2008 @ 1:16 AM PDT

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.

Brian
Quoth Brian on October 17, 2008 @ 2:33 AM PDT

(^[^"]*)" 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.