Replacing quote marks around strings in Vim?

被刻印的时光 ゝ 提交于 2019-12-03 03:06:42

问题


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?


回答1:


You need to use groupings:

:s/\'\(.*\)\'/\"\1\"

This way argument 1 (ie, \1) will correspond to whatever is delimited by \( and \).




回答2:


There's also surround.vim, if you're looking to do this fairly often. You'd use cs'" to change surrounding quotes.




回答3:


%s/'\([^']*\)'/"\1"/g

You will want to use [^']* instead of .* otherwise

'apples' are 'red' would get converted to "apples' are 'red"




回答4:


unless i'm missing something, wouldn't s/\'/"/g work?




回答5:


Just an FYI - to replace all double quotes with single, this is the correct regexp - based on rayd09's example above

:%s/"\([^"]*\)"/'\1'/g



回答6:


You need to put round brackets around the part of the expression you wish to capture.

s/\'\(.*\)\'/"\1"/

But, you might have problems with unintentional matching. Might you be able to simply replace any single quotes with double quotes in your file?




回答7:


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"




回答8:


Presuming you want to do this on an entire file ...

N Mode:

ggvG$ [SHIFT+:]  

X Mode:

'<,'>/'/" [RET]


来源:https://stackoverflow.com/questions/2103643/replacing-quote-marks-around-strings-in-vim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!