bash Vim - 在搜索时捕获字符串并在替换时使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15663057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vim - Capture strings on Search and use on Replace
提问by user1410363
I have a css selector such as:
我有一个 css 选择器,例如:
#page-site-index .toolbar .items {
How do I capture the ".toolbar .items" part and use it on Replace part of Vim S&R, so this selector can turn into:
如何捕获“.toolbar .items”部分并将其用于 Vim S&R 的 Replace 部分,以便此选择器可以变成:
#page-site-index .toolbar .items, #page-site-login .toolbar .items {
Something like:
就像是:
%s:/#page-site-index \(.toolbar .items\)/#page-site-index (the captured string), #page-site-login (the captured string)/g
Btw, I'm using the terminal version of Vim.
顺便说一句,我正在使用 Vim 的终端版本。
回答by Lucas
Use \1... See the wiki here: http://vim.wikia.com/wiki/Search_and_replace
使用\1... 在这里查看 wiki:http: //vim.wikia.com/wiki/Search_and_replace
More explicitly:
更明确:
%s:/#page-site-index \(.toolbar .items\)/#page-site-index , #page-site-login /g
回答by Kent
try this command in your vim:
在你的 vim 中试试这个命令:
%s/\v#(page-site-index )(\.toolbar \.items)/&, #page-site-login /g
you could also use \zs, \zeand without grouping:
你也可以使用\zs, \ze和不分组:
%s/#page-site-index \zs\.toolbar \.items\ze/&, #page-site-login &/g
keep golfing, if the text is just like what you gave in question, you could:
继续打高尔夫球,如果文本就像你给出的问题一样,你可以:
%s/#page-site-index \zs[^{]*\ze /&, #page-site-login &/g
回答by Ingo Karkat
You've already grouped the interesting parts of the regular expression via \(...\)in your attempt. To refer to these captured submatchesinside the replacement part, use \1, \2, etc., where the number refers to the first (opened) capture group, from left to right. There's also \0== &for the entire matched text. See :help /\1for more information.
\(...\)在您的尝试中,您已经将正则表达式中有趣的部分进行了分组。要在替换部分中引用这些捕获的子匹配项,请使用\1、\2等,其中的数字是指从左到右的第一个(打开的)捕获组。整个匹配文本也有\0== &。请参阅:help /\1以获取更多信息。
回答by hek2mgl
First type the :the get into command mode. Then issue the following command:
首先键入:进入命令模式。然后发出以下命令:
%s/#page-site-index .toolbar .items/#page-site-index .toolbar, #page-site-login
.toolbar .items/
Don't care about the formatting, its because of the stackoverflow markdown parser....
不关心格式,这是因为 stackoverflow Markdown 解析器......

