Daniel Que
Daniel Que

Reputation: 1734

Match all words within double quotes

I'd like to have a regular expression to match all words within double quotes.

Consider the line:

the quick "brown fox" jumps

The words brown and fox should be matched, but not the, quick, or jumps.

The following is my first attempt:

".*\zs\w\+\ze.*"

Unfortunately, the greed of .* causes the regex to consume more than I want, and just the x in fox is matched. By using \{-} instead of * (vim's non-greedy equivalent) we get the modified regex:

".\{-}\zs\w\+\ze.*"

But this only matches the first word in the quotes (brown), and not all of them as I'd like.

Can what I'm trying to do be accomplished with a regular expression?

Upvotes: 0

Views: 502

Answers (1)

Sakari Cajanus
Sakari Cajanus

Reputation: 467

Using the positive lookbehind \@<= and positive lookahead \@= you can get the following:

\("\(\w\+ \)*\)\@<=\w\+\(.*"\)\@=

So you demand that zero-width match of \("\(\w\+ \)*\), meaning a quote character followed by 0 or more words followed by space \(\w\+ \) needs to match before the pattern. After the pattern, you can have a sequence of any characters .* followed by quote, but this needs to match as well.

See :h /\@<= and :h /\@= for more examples. \zs can often be used instead of \@<= but in this case it only matches the last word.

Upvotes: 5

Related Questions