VIM - Replace based on a search regex

2019-03-07 07:21发布

问题:

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\*\'$/\\/