开发者

Matching single or double quoted strings in Vim

开发者 https://www.devze.com 2023-03-05 07:20 出处:网络
I am having a hard time trying to match single or double quoted strings with Vim\'s regular expression engine.

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开发者_Python百科 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.


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


look at this post

Replacing quote marks around strings in Vim?

might help in some way


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消