这是 I\xe2\x80\x99m 使用的原材料:
\n\nFirst. \nThis is the second line. \nThe third. \nRun Code Online (Sandbox Code Playgroud)\n\n我想在文本中插入“在4个字符后面插入一些内容”,使其成为
\n\nFirsinsert something behind 4 charactert. \nThisinsert something behind 4 character is the second line. \nThe insert something behind 4 characterthird. \nRun Code Online (Sandbox Code Playgroud)\n\n:%s/^.\\{4}/insert something behind 4 character/g \nRun Code Online (Sandbox Code Playgroud)\n\n该substitute命令不插入文本。如何在每行的第四个字符后面插入这个字符串?
很接近。只需告诉 vim 在模式末尾开始替换即可:
:%s/^.\{4}\zs/insert something behind 4 character/
Run Code Online (Sandbox Code Playgroud)
请注意,我省略了该g标志:它在这里没有什么区别,因为该模式在一行中不会匹配多次。
当然,还有其他方法可以实现,比如
:%s/^.\{4}/&insert something behind 4 character/
Run Code Online (Sandbox Code Playgroud)
也就是说,将前四个字符替换为其自身的副本,后跟新文本。或者
:%s/\%5c\@=/insert something behind 4 character/
Run Code Online (Sandbox Code Playgroud)
或者
:%s/\%5c\&/insert something behind 4 character/
Run Code Online (Sandbox Code Playgroud)
(如果该行只有 4 个字符,后两个将不起作用。)
:help sub-replace-special
:help /\zs
:help /\&
:help /\%c
:help /\@=
Run Code Online (Sandbox Code Playgroud)
并且,一般来说,
:help pattern
Run Code Online (Sandbox Code Playgroud)