简体   繁体   English

正则表达式在Vim中替换多个字符串

[英]Regex replace more than one string in Vim

I have documents with groups of <hr/> tags: 我有带有<hr/>标签组的文档:

<p>stuff</p>
<hr/>
<hr/>
<hr/>
<p>stuff</p>

Grateful for tip how to replace with a single instance of this tag in Vim. 感谢您提示如何在Vim中用该标签的单个实例替换。

You can make <hr/>\\n a group and search for multiples of it, replacing with a single one. 您可以将<hr/>\\n分组,然后搜索它的倍数,而不是一个。 Also note that in Vim you can use different delimiters, which is specially helpful if you're working with slashes for example. 还要注意,在Vim中,可以使用不同的定界符,例如,如果使用斜杠,这将特别有用。 And you don't need to close the substitute command if you don't have flags. 如果没有标志,则不需要关闭替代命令。

:%s#\(<hr/>\n\)\+#\1

With \\v to enable very magic, even more escaping is avoided. 使用\\v启用魔术,可以避免更多的转义。 However the < and > will be treated as special word boundaries. 但是, <>将被视为特殊单词边界。 So you have to escape them instead. 因此,您必须逃脱它们。

:%s#\v(\<hr/\>\n)+#\1

And of course, if the only duplicated lines in your file are those tags, this is enough as well: 当然,如果文件中唯一重复的行就是这些标记,那么这也足够了:

:%!uniq

You can use this search-replace in vim : 您可以在vim使用此搜索替换:

:%s/<hr\/>\n\(<hr\/>\n\)\+/\1/

<hr\\/>\\n\\(<hr\\/>\\n\\)\\+ will find 2 or more lines containing <hr/> and we replace it using \\1 which is <hr/>\\n . <hr\\/>\\n\\(<hr\\/>\\n\\)\\+将找到2个或更多包含<hr/> ,我们使用\\1替换它,它是<hr/>\\n

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

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