简体   繁体   English

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

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

I have a text file with a structure like this: 我有一个文本文件,其结构如下:

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

So each line either contains "normal" text or a comment starting with "#". 因此,每一行都包含“普通”文本或以“#”开头的注释。 I want this text to be replaced using regex, so that each "text"-line gets a comment line above it. 我希望使用正则表达式替换此文本,以便每个“文本”行在其上方都有一条注释行。 The result should be something like: 结果应该是这样的:

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

However, I'm not able to create a working regex although I spent really much time. 但是,尽管我花了很多时间,但我无法创建有效的正则表达式。 There's always at least one special case where my regex fails. 至少在一种特殊情况下,我的正则表达式会失败。 The best one I was able to create is: 我能够创造的最好的是:

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

This one works perfectly fine (except for the first line), if I run it twice. 如果我运行两次,则该脚本运行良好(除了第一行)。 But running it only once skips some lines, eg I get this result: 但是只运行一次会跳过一些行,例如,我得到以下结果:

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

Notice that there's no line inserted between " the " and " lazy ". 请注意,没有线之间“ ”和“ 懒惰 ”插入。 The reason for this is, that the term "the" is a part of the regex group and part of the replaced text and so it won't be parsed by regex again. 这样做的原因是,术语“ the”是regex组的一部分,并且是替换文本的一部分,因此regex不会再次对其进行解析。

Is there any possibility (well I bet there is and I'm just not able to find it...) to solve this issue? 是否有解决此问题的可能性(我敢打赌,我只是找不到它...)? I realize that checking the first line is another problem, too. 我意识到检查第一行也是另一个问题。 It would be great if this could be recognized, too, however this is currently not my main focus of attention. 如果也可以认识到这一点,那就太好了,但是目前这不是我的主要关注重点。

You can use a negative look-behind, \\@<! 您可以使用否定的后缀\\@<! , to ensure the previous line is not a comment. ,以确保上一行不是注释。

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

For more information see: 有关更多信息,请参见:

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

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

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

OR :%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)

Try this.Replace by #auto comment\\n$1$2 .See demo. 试试这个。用#auto #auto comment\\n$1$2代替。请参阅演示。

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

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

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