问题
Perl provides quotemeta function, as well as the possibility to surround strings using the \Qlots-of-meta-characters\E construct, to make sure that all the characters between \Q and \E are interpreted as literals.
Very often I search strings full of meta characters in Vim. It's counterproductive to escape every special character individually. Is there anything like /\Qstring-to-search\E in Vim, which would make life easier?
回答1:
You can use /\Vstring-to-search.
There are two caveats:
\is special. You can still use all regex metacharacters by putting a\in front of them.- There is no
\Eequivalent.\Vaffects the rest of the regex.
See :help /\V.
You could combine this with the code from the answer in https://stackoverflow.com/a/676619/1848654 as follows:
vnoremap <C-f> "hy/\V<C-r>=substitute(@h,'[\/]','\\&','g')<cr>
The idea is:
- Copy ("yank") the selected text into register
h:"hy - Start search mode:
/ - Prefill the beginning of the regex:
\V - Insert the contents of a register:
<C-r> - Don't use a real register; take the result of evaluating an expression instead:
= - Our expression (terminated by
<cr>) is:substitute(@h,'[\/]','\\&','g')- Take the contents of the
hregister:@h - Apply a substitution. Insert a
\before every\and/:substitute(...,'[\/]','\\&','g')
- Take the contents of the
来源:https://stackoverflow.com/questions/50629000/how-to-efficiently-escape-meta-characters-in-vim-search