简体   繁体   English

是否可以在vim中替换匹配的模式?

[英]Is is possible to substitute the matched pattern in vim?

Every time before I replace pattern1 with pattern2 , I usually use /pattern1 to confirm the regex is the right one. 每次在用pattern2替换pattern1 pattern2 ,我通常使用/pattern1来确认正则表达式是正确的。 When doing the actual substitution, however, I have to use :%s/pattern1/pattern2/g (Suppose I need to do the global replacement). 但是,在进行实际替换时,我必须使用:%s/pattern1/pattern2/g (假设我需要进行全局替换)。 This is annoying and may fail due to typos. 这很烦人,可能由于错别字而失败。

So is there a convenient way to substitute the matched pattern1 ? 那么是否有一种方便的方法来替代匹配的pattern1

// is last search :%s//replacement/g will do what you want. //是最后一次搜索:%s//replacement/g将执行您想要的操作。

however you could also think about %s/pattern1/pattern2/gc or %s/p1/p2/gn 但是您也可以考虑%s/pattern1/pattern2/gc%s/p1/p2/gn

The null string in the first half of the s command defaults to the last searched pattern. s命令的前半部分中的空字符串默认为最后搜索的模式。

So 所以

g/fred/s//mary/g

changes all instances of fred to mary. 将fred的所有实例更改为mary。

只需使用一个空模式:

:%s//pattern2/g

I think that: 我觉得:

:.,.+3s//repl/g :。,。+ 3s // repl / g

should replace every occurence of the current pattern in the next 3 lines with repl. 应该用repl替换接下来3行中当前模式的每次出现。

您可以使用:%s/pattern/replace/c (注意尾随c ),vim会要求您进行确认。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM