Substitute in vim, with special characters

走远了吗. 提交于 2019-12-11 08:50:39

问题


I am trying to use substitute command in vim to enclose all occurences of a particular pattern

\cite{author1}
\cite{author2}

with

(\cite{author1})
(\cite{author2})

Based on other answers in stack exchangeI used the following vim command

%s/\\cite{(\w\+)}/(\\cite{\1})/g

But, no luck. It says "no matches found". I put two back slashes, one of which is supposed to be the escape character. Kindly help.

I know I could use some other editor and finish the job, but I want to know my mistake. Thank you.


回答1:


please escape ()

%s/\\cite{\(\w\+\)}/(\\cite{\1})/g



回答2:


You do not need a capture group to get the entire match. You can use \0 or & for the whole match in the replacement portion of your substitution.

:%s/\\cite{\w\+}/(&)/g

If you do want to use a capture group, then you need to escape the capture group/parenthesis.

:%s/\(foo\)/(\1)/g

For more help see:

:h :s%
:h /magic



回答3:


As mentioned, normally you need escape the parentheses.

You can use very magic mode (\v) to make the regex simpler; removing the need to escape lots of the regex parts, including the parentheses for capturing:

%s/\v(\\cite\{\w+\})/(\1)/g



回答4:


Knowing what every sign in a regular expression does in vim is sometimes very difficult, especially for all the modes and configuration variables that this depends on. For that reason, it is very important to have visual feedback about what text are we really matching in any moment while crafting regular expressions.

If you work with neovim, there is a special option called inccommand that you can enable to live preview the matches and substitution. That way you can figure out you errors more quickly. This feature is very likely to be included also in vim in the future, but independently of that, you can also use simple vim to give you visual feedback if you enable the option incsearch.

With incsearch set, you can watch the matches of / and ? while you write them just to be sure that the pattern is correct. Later you can exploit a nice feature from the substitution: if you leave the first section empty, the last search will be used.

So you could first make the search:

/\\cite{\w\+}/(&)/g

In the meantime, vim will be showing you the matched text visually. Once you are sure that the pattern is correct press enter, and finally type:

:%s//(\1)<Enter>

Also, in case you want something more powerful than this simple hack, you can go for my plugin Extend.vim, that can do that and much more with great visual feedback.



来源:https://stackoverflow.com/questions/44798719/substitute-in-vim-with-special-characters

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