VIM - 基于搜索正则表达式替换 [英] VIM - Replace based on a search regex

查看:68
本文介绍了VIM - 基于搜索正则表达式替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多条(1000 多条)记录的文件,例如:

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 \.*'

我不能做 :%s//s[w|l].*[0-9].*$/\\\\\.\*' 因为它会替换所有字符串,我需要的只是替换它的末尾.'至\.'

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

所以文件输出就像:

lbc3\\.*'

ssa2\\.*'


lie1\\.*'

sld0\\.*'

ssdasd\\.*'

谢谢.

推荐答案

一般来说,解决方案是使用捕获.将 \(...\) 放在与您要保留的内容匹配的正则表达式部分周围,并使用 \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\\.*'/

由于您实际上只是在您没有更改的两个字符串之间插入一个反斜杠,您可以使用第二组括号和 \2 作为第二组:

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/

或者,您可以使用 \zs\ze 来分隔要替换的字符串部分:

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

这篇关于VIM - 基于搜索正则表达式替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆