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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With