Vim - Capture strings on Search and use on Replace

若如初见. 提交于 2019-12-19 19:12:35

问题


I have a css selector such as:

#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:

#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.


回答1:


Use \1... See the wiki here: http://vim.wikia.com/wiki/Search_and_replace

More explicitly:

%s:/#page-site-index \(.toolbar .items\)/#page-site-index \1, #page-site-login \1/g



回答2:


try this command in your vim:

%s/\v#(page-site-index )(\.toolbar \.items)/&, #page-site-login \2/g

you could also use \zs, \ze and without grouping:

%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



回答3:


You've already grouped the interesting parts of the regular expression via \(...\) in your attempt. To refer to these captured submatches inside 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 /\1 for more information.




回答4:


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....



来源:https://stackoverflow.com/questions/15663057/vim-capture-strings-on-search-and-use-on-replace

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