vimscript match combine \V with word boundaries

144 Views Asked by At

I have the problem that I want to combine the \V and word boundaries in the match function, like this:

let index = match(line, "\\<\V".pattern."\v\\>")

the following works perfect:

let index = match(line, "\\<".pattern."\\>")

Does anyone have an idea how to combine those two things?

1

There are 1 best solutions below

1
On BEST ANSWER

Even with \V, the backslash still has a special meaning, so \<...\> should continue to work. I personally would put the \V at the front, and use single quotes to avoid doubling the backslashes:

let index = match(line, '\V\<'.pattern.'\>')

I guess you intent to match any literal text in pattern as whole words. For that to work, you still need to escape backslashes. This is how it's usually done:

let index = match(line, '\V\<'.escape(pattern, '\').'\>')

The reason that this may fail to match is when pattern does not start / end with a keyword character. If you need to handle that, you'd have to check pattern first and only conditionally add the \< and \>. (The check can by done by matching with \k.)