问题
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:
- Search for
foo %s//\=@a/g(or highlight some text and start typing:sto substitute only in that range)
来源:https://stackoverflow.com/questions/3922384/use-a-register-value-as-search-pattern