如何替换 vi 中的匹配分隔符?
我有一些匹配分隔符的文本(在本例中是花括号,文本恰好是 LaTeX,这只是偶然的):
\nb{\vec{n},\vec{y}} \in \vec{z}
我想做的是全局替换 \nb{...}
与 (...)
,同时尊重分隔符的嵌套。即,结果应该是
(\vec{n},\vec{y}) \in \vec{z}
,而不是
(\vec{n},\vec{y}} \in \vec{z)
:%s/\\nb{\(.*\)}/(\1)/g
产生的结果。标准正则表达式无法处理匹配的分隔符,所以我没想到这种方式会起作用。我可以使用一些特定于 vi 的技巧来做到这一点吗?
I have some text which has matched delimiters (in this case, curly braces, and the text happens to be LaTeX, which is only incidental):
\nb{\vec{n},\vec{y}} \in \vec{z}
What I'd like to do is globally replace \nb{...}
with (...)
, while respecting the nesting of delimiters. I.e., the result should be
(\vec{n},\vec{y}) \in \vec{z}
and not
(\vec{n},\vec{y}} \in \vec{z)
which is what would be produced by :%s/\\nb{\(.*\)}/(\1)/g
. Standard regular expressions can't handle matched delimiters, so I wasn't expecting this way to work. Is there some vi-specific trick I can use to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您安装了 surround.vim 那么以下应该可以解决问题
如果您没有:
概述
创建搜索
\nb{
的递归宏,将光标定位在{
内,将}{
替换为( )
的。细节的荣耀
:set nowrapscan
这可以防止搜索在文件周围循环。:let @q="..."
将我们的宏存储在q
寄存器中/\m\nb{/e+1
搜索\nb{
并将光标定位在{
cs{)
之后,环绕版本只会更改周围的{
with)
@q
再次运行宏"
因此必须转义一些内容,以便它们正常工作。gg@q
转到文件顶部并执行寄存器q
中的宏非环绕版本此处略有不同
yi{
复制{
的"_ca{()
更改文本内部并包括{
并替换为()
"0P
将我们刚刚复制的内容粘贴到()
中If you have surround.vim installed then the following should do the trick
If you do not:
Overview
Create a recursive macro that searches for
\nb{
, positions the cursor just inside the{
, replace the}{
's with()
's.Glory of Details
:set nowrapscan
this prevents searches from looping back around the file.:let @q="..."
store our macro inside theq
register/\m\nb{/e+1
searches for\nb{
and positions the cursor after the{
cs{)
the surround version will just change the surrounding{
with)
@q
run the macro again"
so must escape a few things so they work correctly.gg@q
go to the top of the file and execute the macro in registerq
The non surround version varies a bit here
yi{
copy the text inside{
's"_ca{()<esc>
change the text inside and including the{
's and replace with()
"0P
paste what we just copied inside the()
我将使用以下
:global
命令。输入
^M
作为 Ctrl+V,Enter。I would use the following
:global
command.Type
^M
as Ctrl+V, Enter.