alfredodeza
alfredodeza

Reputation: 5188

Matching single or double quoted strings in Vim

I am having a hard time trying to match single or double quoted strings with Vim's regular expression engine.

The problem is that I am assigning the regular expression to a variable and then using that to play with matchlist.

For example, let's assume I know I am in a line that contains a quoted string and I want to match it:

let regex = '\v"(.*)"'

That would work to match anything that is double-quoted. Similarly, this would match single quoted strings:

let regex = "\v'(.*)'"

But If I try to use them both, like:

let regex = '\v['|"](.*)['|"]'

or

let regex = '\v[\'|\"](.*)[\'|\"]'

Then Vim doesn't know how to deal with it because it thinks that some quotes are not being closed in the actual variable definition and it messes up the regular expression.

What would be the best way to catch single or double quoted strings with a regular expression?

Maybe (probably!) I am missing something really simple to be able to use both quotes and not worry about the surrounding quotes for the actual regular expression.

Note that I prefer single quotes for regular expression because that way I do not need to double-backslash for escaping.

Upvotes: 4

Views: 5204

Answers (3)

qingchen
qingchen

Reputation: 1

This is a workable script I write for syntax the quoted strings.

syntax region myString start=/\v"/ skip=/\v(\\[\\"]){-1}/ end=/\v"/
syntax region myString start=/\v'/ end=/\v'/

You may use \v(\\[\\"]){-1} to skip something.

Upvotes: -2

Peter Rincker
Peter Rincker

Reputation: 45107

You need to use back references. Like so:

let regex = '\([''"]\)\(.\{-}\)\1'

Or with very-magic

let regex = '\v([''"])(.{-})\1'

Alternatively you could use (as it will not mess with your sub-matches):

let regex = '\%("\([^"]*\)"\|''\([^'']*\)''\)'

or with very magic:

let regex = '\v%("([^"]*)"|''([^'']*)'')'

Upvotes: 10

AabinGunz
AabinGunz

Reputation: 12347

look at this post

Replacing quote marks around strings in Vim?

might help in some way

Upvotes: 1

Related Questions