How to efficiently escape meta-characters in vim search

妖精的绣舞 提交于 2020-01-15 08:18:41

问题


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 \E equivalent. \V affects 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 h register: @h
    • Apply a substitution. Insert a \ before every \ and /: substitute(...,'[\/]','\\&','g')


来源:https://stackoverflow.com/questions/50629000/how-to-efficiently-escape-meta-characters-in-vim-search

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!