I want to create a regex that matches strings within single or double quotes in vim and that considers the fact that some strings might have escaped single quotes or double quotes.
So far, I've found this answer in an stackoverflow question which does the same thing but in Javascript regex flavor. By using the logic of that regex, I tried to write a regular expression but in vim regex flavor. The reasoning I followed for translating the javascript regex to a vim regex is explained below
(["'])(?:(?=(\\?))\2.)*?\1
(["'])
- Definition: capture group of single or double quotes
vim
equivalent:(["'])
(?:(?=(\\?))\2.)
- Definition: Non-capturing group of
(?=(\\?))\2.
vim
equivalent:%((\\?)@=\2.)
(?=(\\?))
- Definition: Positive lookahead of
(\\?)
vim
equivalent:(\\?)@=
- Definition: Positive lookahead of
\2
- Definition: Backreference to
\\?
vim
equivalent:\2
- Definition: Backreference to
.
- Definition: Matches any character different from line breaks
vim
equivalent:.
- Definition: Non-capturing group of
*?
- Definition: Non-greedy operator of
(?:(?=(\\?))\2.)
vim
equivalent:{-}
- Definition: Non-greedy operator of
\1
- Definition: Backreference to
["']
vim
equivalent:\1
- Definition: Backreference to
By following the reasoning explained above, the following Javascript regex
(["'])(?:(?=(\\?))\2.)*?\1
would be equivalent to the following vim regex
/\v(["'])%((\\?)@=\2.){-}\1
However, this regex does not completely mimick the behavior of the Javascript regex, because it matches some patterns (see image below) that are not matched by the Javascript regex presented above (see what the latter matches here).
Why is the vim regex matching any character that follows a single quote or a double quotes given that the last character of the regex is a backreference to a single quote or a double quote?
/\(\w\).\1
matches aba, xax, 9_9 but not aa, abc, abba, etc.