3

I am trying to write a regular expression that will match all double quoted strings across newlines. I have been fiddling around with the following pattern but it seems to only match strings on the same line.

/\v"\zs(.*|\n*)\ze"

The pattern should match something like this:

"This is an example
 of a multi, line -- %123 string with
 some random 123 symbol's 
 `inside` \\//><>< of it"

What is wrong with the pattern I have?

8

You can simply use

/\v"([^"]|\n)*"

That is,

"       quotation mark
(...)*  followed by 0 or more of...
  [^"]    character that is not a quotation mark
  |\n     or a newline
"       followed by another quotation mark

This will also "work" for "multiple" strings "in the same" file, because [^"] makes sure that the regex never matches past another quotation mark.


Here's an alternative that's shorter but a bit harder to read:

/\v"\_.{-}"

Explanation:

"    quotation mark
\_.  any character, including a newline (see `:help /\_.')
{-}  non-greedy version of * (see `:help non-greedy')
"

This also works for multiple strings in the same file due to {-}, which is the lazy equivalent of *.

  • Thank you. For educational purposes, can you add how to do this without the use of [^"]? – user489 Feb 19 '15 at 22:01
  • @merb Sure, edited in an alternative that uses \_.. – Doorknob Feb 19 '15 at 22:03
  • Nice! Although perhaps one should improve slightly so as not to match escaped quotes? – Karl Yngve Lervåg Feb 20 '15 at 8:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy