2

I have a following text:

Search items: [http://vimdoc.net/search?q=/\\][s]

...
[s]: http://vimdoc.net/search?q=/\\

Now I would like to find the http://vimdoc.net/search?q=/\\ string from this text. I can do this with \Vhttp:\/\/vimdoc.net\/search?q=\/\\\\ search pattern. However, I would expect \Vhttp:\/\/vimdoc.net\/search\?q=\/\\\\ to also work(? is escaped). I mean in case of \V, the backslash(\) character has a special meaning. Could somebody please explain this.

5

According to the manual:

Use of "\V" means that in the pattern after it only the backslash and the terminating character (/ or ?) has a special meaning. "very nomagic"

The phrasing is somewhat misleading. What this actually means is that you always need to escape the backslash (\ -> \\), but you only need to escape / and ? when they are used as terminating characters. Namely:

  • To search forward you have to start with /, so / becomes a terminating character. Thus you need to escape / (and \), but not ?:

    /\Vhttp:\/\/vimdoc.net\/search?q=\/\\\\
    
  • To search backwards you have to start with ?, so ? becomes a terminating character. Thus you need to escape ? (and \), but not /:

    ?\Vhttp://vimdoc.net/search\?q=/\\\\
    

However, when you do a replace you can avoid the leaning toothpick syndrome almost entirely, by choosing a terminating character that is neither / nor ?. Here only \ needs to be escaped:

:s!\Vhttp://vimdoc.net/search?q=/\\\\!...!

You can still minimise your pain even when searching forward. Since you have way more slashes than question marks in your pattern you can start by searching backwards first, just to set the pattern, then change the search direction:

?\Vhttp://vimdoc.net/search\?q=/\\\\
/
n

Another consequence is that you only ever need to escape \ when using \V patterns with the search() function:

:echo search('\Vhttp://vimdoc.net/search?q=/\\\\', 'c')
| improve this answer | |
  • Thanks! So if I search forward(using /\V), then I can escape(`) only the backslash (`) and forwardslash(/)? And thus, in case of forward search, \? has a literal meaning? – Martin Aug 15 '16 at 20:34
  • 1
    @Martin I can't really parse your comment, but yes, I think you got it. :) – Sato Katsura Aug 15 '16 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.