繁体   English   中英

Vim正则表达式:在所有不以“#”开头的行上添加行

[英]Vim regex: add line above all lines not starting with “#”

我有一个文本文件,其结构如下:

The quick  
#a comment
brown 
fox jumps  
#another comment
over  
the 
lazy
#yet another comment
dog

因此,每一行都包含“普通”文本或以“#”开头的注释。 我希望使用正则表达式替换此文本,以便每个“文本”行在其上方都有一条注释行。 结果应该是这样的:

#auto comment
The quick  
#a comment
brown 
#auto comment
fox jumps  
#another comment
over  
#auto comment
the 
#auto comment
lazy
#yet another comment
dog

但是,尽管我花了很多时间,但我无法创建有效的正则表达式。 至少在一种特殊情况下,我的正则表达式会失败。 我能够创造的最好的是:

:%s/^\([^#].*\)\n\([^#].*\)$/\1\r#auto comment\r\2/g

如果我运行两次,则该脚本运行良好(除了第一行)。 但是只运行一次会跳过一些行,例如,我得到以下结果:

The quick
#a comment
brown
#auto comment
fox jumps
#another comment
over
#auto comment
the
lazy
#yet another comment
dog

请注意,没有线之间“ ”和“ 懒惰 ”插入。 这样做的原因是,术语“ the”是regex组的一部分,并且是替换文本的一部分,因此regex不会再次对其进行解析。

是否有解决此问题的可能性(我敢打赌,我只是找不到它...)? 我意识到检查第一行也是另一个问题。 如果也可以认识到这一点,那就太好了,但是目前这不是我的主要关注重点。

您可以使用否定的后缀\\@<! ,以确保上一行不是注释。

%s/\(^#.*\n\)\@<!\_^[^#]/#auto comment\r&

有关更多信息,请参见:

:h /\@<!
:h /\_^
:h s/\\&

使用:: :%s/^\\([^#].*\\)/#auto comment\\r\\1/g

然后运行:: :%s/^\\(#.*\\)\\n#.*/\\1/g

:%s/^\\([^#].*\\)/#auto comment\\r\\1/g | %s/^\\(#.*\\)\\n#.*/\\1/g :%s/^\\([^#].*\\)/#auto comment\\r\\1/g | %s/^\\(#.*\\)\\n#.*/\\1/g

([^#\n]+\n#[\w ]+?\n[^\n]+(?:\n|$))|^([^\n]+\n)

试试这个。用#auto #auto comment\\n$1$2代替。请参阅演示。

http://regex101.com/r/lZ5mN8/24

暂无
暂无

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

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