使用vim附加到中间带有单词的模式的末尾

时间:2016-09-15 21:57:03

标签: vim

我有一个过时的文件,需要更新。这些名字有所改变,我想用一次替换来清理它们。

这就是我想要完成的事情:

foo.foo_[single word] -> foo_bar.foo_[single word]_bar

其中单个单词是n个字符的字符串。在文件中,它们总是以下划线开头,但它需要附加“_bar”。总有一个“。”在这些情况之后,我认为以下内容可能有效:

%s/foo\.foo_*\./foo_bar\.foo_*_bar\./g

可悲的是,第一部分甚至不符合我的要求,所以我回到原点。

2 个答案:

答案 0 :(得分:0)

我会先改变:

Math.Floor

然后

foo_[word] -> foo_[word]_bar

即:

foo. -> foo_bar.

答案 1 :(得分:0)

有许多方法可以给猫皮肤,但是应该遵循这个技巧

%s/\vfoo.foo_(\w+)/foo_bar.foo_\1_bar/gc

松散地转化为

\v             Very Magic (:help magic)
foo.foo_       Search for exact string
(\w+)          Search for a "word" and store in a backreference
/foo_bar.foo   Replace search pattern with this exact string
\1             appended with backreference 1
_bar           appended with _bar

或者如果您不想在替换部分中重复搜索,您可以通过反向引用来解决问题并使用

%s/\v(foo)\.foo_(\w+)/\1_bar.\1_\2_bar/gc

你缺少的最重要的部分是

  • 使用反向引用(:helpgrep backref)
  • 使用字符类(:h \ w)
  • 使用重复(_ *正在搜索0或更多下划线。你可能意味着_。*)