VIM - Replace based on a search regex

谁说胖子不能爱 提交于 2019-12-04 07:39:11

问题


I've got a file with several (1000+) records like :

lbc3.*'

ssa2.*'

lie1.*'

sld0.*'

ssdasd.*'

I can find them all by :

/s[w|l].*[0-9].*$

What i want to do is to replace the final part of each pattern found with \.*'

I can't do :%s//s[w|l].*[0-9].*$/\\\\\.\*' because it'll replace all the string, and what i need is only replace the end of it from .' to \.'

So the file output is llike :

lbc3\\.*'

ssa2\\.*'


lie1\\.*'

sld0\\.*'

ssdasd\\.*'

Thanks.


回答1:


In general, the solution is to use a capture. Put \(...\) around the part of the regex that matches what you want to keep, and use \1 to include whatever matched that part of the regex in the replacement string:

   s/\(s[w|l].*[0-9].*\)\.\*'$/\1\\.*'/

Since you're really just inserting a backslash between two strings that you aren't changing, you could use a second set of parens and \2 for the second one:

   s/\(s[w|l].*[0-9].*\)\(\.\*'\)$/\1\\\2/

Alternatively, you could use \zs and \ze to delimit just the part of the string you want to replace:

   s/s[w|l].*p0-9].*\zs\ze\*\'$/\\/


来源:https://stackoverflow.com/questions/27527749/vim-replace-based-on-a-search-regex

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