在 Vim 中替换字符串周围的引号?
我有类似于
的内容,需要将单引号更改为双引号。我尝试了 :s/\'.*\'/\"\0\"
但最终产生了
>。将 \0
替换为 \1
只会在双引号内产生一个空白字符串 - 是否缺少一些特殊语法,我只需要生成找到的字符串( "Hello There") 内的引号分配给 \1
?
I have something akin to <Foobar Name='Hello There'/>
and need to change the single quotation marks to double quotation marks. I tried :s/\'.*\'/\"\0\"
but it ended up producing <Foobar Name="'Hello There'"/>
. Replacing the \0
with \1
only produced a blank string inside the double quotes - is there some special syntax I'm missing that I need to make only the found string ("Hello There") inside the quotation marks assign to \1
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
除非我遗漏了一些东西,否则
s/\'/"/g
不起作用吗?unless i'm missing something, wouldn't
s/\'/"/g
work?仅供参考 - 将所有双引号替换为单引号,这是正确的正则表达式 - 基于上面 rayd09 的示例
Just an FYI - to replace all double quotes with single, this is the correct regexp - based on rayd09's example above
您需要将要捕获的表达式部分放在圆括号内。
但是,您可能会遇到无意匹配的问题。您是否可以简单地将文件中的任何单引号替换为双引号?
You need to put round brackets around the part of the expression you wish to capture.
But, you might have problems with unintentional matching. Might you be able to simply replace any single quotes with double quotes in your file?
您的想法是正确的 - 您希望将
"\1"
作为替换子句,但您需要首先将“Hello There”部分放入捕获组 1 中(0 是整个捕获组)匹配)。尝试::%/'\(.*\)'/"\1"
You've got the right idea -- you want to have
"\1"
as your replace clause, but you need to put the "Hello There" part in capture group 1 first (0 is the entire match). Try::%/'\(.*\)'/"\1"
Shift + V 进入视觉块模式。突出显示要从中删除单引号的代码行。
然后按键盘上的 :
然后输入
s/'//g
按 Enter。
完毕。你赢了。
Shift + V to enter visual block mode. Highlight the lines of code you want to remove single quotes from.
Then hit : on keyboard
Then type
s/'//g
Press Enter.
Done. You win.
假设您想对整个文件执行此操作...
N 模式:
X 模式:
Presuming you want to do this on an entire file ...
N Mode:
X Mode:
如果你想公平地做到这一点,还有 surround.vim经常。您可以使用
cs'"
更改周围的引号。There's also surround.vim, if you're looking to do this fairly often. You'd use
cs'"
to change surrounding quotes.您需要使用分组:
这样参数 1(即 \1)将对应于由 \( 和 \) 分隔的任何内容。
You need to use groupings:
This way argument 1 (ie, \1) will correspond to whatever is delimited by \( and \).
%s/'\([^']*\)'/"\1"/g
您需要使用
[^']*
而不是.*
否则'apples' are 'red'
将转换为"apples' are 'red"
%s/'\([^']*\)'/"\1"/g
You will want to use
[^']*
instead of.*
otherwise'apples' are 'red'
would get converted to"apples' are 'red"