简体   繁体   English

Vim中的正则表达式 - 在编号行之前插入空白行

[英]Regex in Vim- inserting blank line before numbered lines

I have following text: 我有以下文字:

Title line
1. First list
First line
Second line
2. Second list
Oranges
Mangoes
3. Stationary
Pen
Pencils
Etc

I want to add a blank line before every numbered line, so that above text looks like following: 我想在每个编号行之前添加一个空行,以便上面的文字如下所示:

Title line

1. First list
First line
Second line

2. Second list
Oranges
Mangoes

3. Stationary
Pen
Pencils
Etc

I tried following code but it is not working: 我尝试了以下代码,但它无法正常工作:

%s/^(\d)/\r\1/g

and

%s/(^\d)/\r\1/g

and

% s/^([0-9])/\\r\\1/gc s/^([0-9])/\\r\\1/gc

Where is the problem and how can this be solved. 问题在哪里以及如何解决。 Thanks for your help. 谢谢你的帮助。

You should escape parentheses within a VIM syntax in order to mean it a special cluster: 您应该在VIM语法中转义括号,以表示它是一个特殊的集群:

%s/^\(\d\)/\r\1/g

Or use an end of match zero-width assertion ( \\ze ) token: 或者使用匹配结束零宽度断言\\ze )令牌:

%s/^\ze\d/\r

To use capture group () without having to escape them, use \\v very magic (See :h /magic ) 要使用捕获组()而不必转义它们,请使用\\v very magic(参见:h /magic

:%s/\v^(\d)/\r\1/

Note that g flag is redundant as there can be only one match at beginning of line 请注意, g标志是多余的,因为在行的开头只能有一个匹配

As entire matched string is needed in replacement section, one can simply use & or \\0 without needing explicit capture group 由于替换部分需要整个匹配的字符串,因此可以简单地使用&\\0而无需显式捕获组

:%s/^\d/\r&/


Mentioned in comments 评论中提到

:g/^\d/norm O

The g command allows filtering lines and executing command on those lines, like norm O to open new line above. g命令允许过滤行并在这些行上执行命令,如norm O打开上面的新行。 Default range is entire file, so % is not needed 默认范围是整个文件,因此不需要%

With substitute command, this would be :g/^\\d/s/^/\\r/ 使用substitute命令,这将是:g/^\\d/s/^/\\r/

See :h :g and :h ex-cmd-index for complete list of commands to use with :g 请参阅:h :g:h ex-cmd-index以获取要使用的命令的完整列表:g

You can use the global command, :g to execute an empty :put on each line before the matching number, ^\\d . 你可以使用全局命令, :g来执行一个空:put在匹配的数字之前:put每一行, ^\\d

:g/^\d/pu!_

Note: Using the blackhole register, "_ , combined with :put to give us the empty line. 注意:使用黑洞寄存器, "_ ,结合:put给我们空行。

For more help see: 有关更多帮助请参阅:

:h :g
:h /\d
:h :put
:h quote_

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

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