Use a register value as search pattern

百般思念 提交于 2019-12-20 11:18:09

问题


I wish to use the content of a register as search pattern in Vim.

I would like to do this from the command line so I cannot use the <c-r> syntax since that assumes an interactive session.

It is possible to use a register as a replace pattern, like this

:%s/foo/\=@a/g

However using this syntax as a search pattern does not work

:%s/\=@a/foo/g 

it outputs

E64: \= follows nothing
E476: Invalid command

回答1:


I don't think it's possible directly, but you can use :exe to achieve this:

:exe '%s/' . @a . '/foo/g'



回答2:


In a pattern (not the replacement part), \= stands for “0 or 1 time” (it is a synonym for \? put should be preferred over \? since the latter means a literal ? when looking backwards.

See :help /\= and help pattern for more details.

Why not :

let @/=@a
%s//foo/g



回答3:


You can do this with the / register

This doesn't solve the general problem, but it appears to me that the / register is special in this regard: if you leave the search term blank, it will use whatever is in the / register; namely, whatever you searched for last.

So if you want to replace foo with the contents of @a, you could do this:

  1. Search for foo
  2. %s//\=@a/g (or highlight some text and start typing :s to substitute only in that range)


来源:https://stackoverflow.com/questions/3922384/use-a-register-value-as-search-pattern

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