在 Vim 中搜索/替换
我想删除所有符合此正则表达式的方括号:\[.*\].*{
,但我只想删除括号,而不是后面的内容 - 即,我想仅当括号后跟左大括号时才删除括号及其内部内容。
我如何使用 Vim 的搜索/替换来做到这一点?
I want to delete all occurrences of square brackets that conform to this regex: \[.*\].*{
, but I only want to delete the brackets, not what follows - i.e., I want to delete the brackets and what's inside them, only when they are followed by an opening curly brace.
How do I do that with Vim's search/replace?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
\zs
和\ze
设置匹配的开始和结束。:%s/\zs\[.*\]\ze.*{//g
应该可以。您告诉 Vim 将
\zs
和\ze
之间的内容替换为空字符串。(请注意,您需要在 Vim 二进制文件中编译 +syntax 选项)
有关更多信息,请参阅
:help /\zs
或:help pattern
编辑 :实际上 \zs 在这种情况下不是必需的,但我将其保留用于教育目的。 :)
You can use
\zs
and\ze
to set the beginning and the end of the match.:%s/\zs\[.*\]\ze.*{//g
should work.You are telling Vim to replace what is between
\zs
and\ze
by an empty string.(Note that you need the +syntax option compiled in your Vim binary)
For more information, see
:help /\zs
or:help pattern
Edit : Actually \zs is not necessary in this case but I leave it for educational purpose. :)
如果将正则表达式的最后一位括在括号中,则可以在替换中重复使用它:
\1 引用括号中的正则表达式部分。
我喜欢在搜索中使用搜索字符串之前构建搜索字符串,并替换以确保在更改文档之前它是正确的:
这将突出显示您将替换的所有内容。
然后运行不带搜索词的 %s 命令以使其重新使用上一个搜索词
If you surround the last bit of your regex in parenthesis you can re-use it in your replace:
The \1 references the part of the regex in parenthesis.
I like to build my search string before I use it in the search and replace to make sure it is right before I change the document:
This will highlight all the occurrances of what you will replace.
Then run the %s command without a search term to get it to re-use the last search term
怎么样:
请注意,
\ze
项标记了匹配的结束,因此后面的任何内容都不会被替换。How about:
Note that the
\ze
item marks the end of the match, so anything that follows is not replaced.这将在当前文件上运行您的正则表达式:
:%s/\[.*\]\(.*{\)/\1/g
This will run your regex on the current file:
:%s/\[.*\]\(.*{\)/\1/g