Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching single or double quoted strings in Vim

Tags:

regex

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.

like image 771
alfredodeza Avatar asked Feb 24 '23 06:02

alfredodeza


2 Answers

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%("([^"]*)"|''([^'']*)'')'
like image 177
Peter Rincker Avatar answered Mar 04 '23 22:03

Peter Rincker


look at this post

Replacing quote marks around strings in Vim?

might help in some way

like image 31
AabinGunz Avatar answered Mar 05 '23 00:03

AabinGunz