Reputation: 1003
Consider the below line for example
'{"place":"buddy's home"}'
I want to replace the single quote in buddy's
only. Single quotes at the start and end of line had to be intact. So the resulting line would look like.
'{"place":"buddy\'s home"}'
There could be multiple lines with multiple occurrences of such single quotes in each line. I have to escape all of them except at the start and end of line.
I'm able to find out such pattern using vim regex :/.'.
This pattern ensures that single quote is surrounded by two characters and is not at start or at the end of line. But I'm having trouble how to replace the y's
into y\'s
at all places.
Upvotes: 2
Views: 905
Reputation: 4579
:%s/\(.\)'\(.\)/\1\\'\2/gc
:%s/
substitute over the whole buffer (see :help range
to explain the %
)\(.\)
match a character and save it in capture group 1 (see :help \(
)'
a literal '
\(.\)
match a character and save it in capture group 2/
replace by\1
capture group 1 (see :help \1
)\\'
this is a \'
(you need to escape the backslash)\2
capture group 2/gc
replace globally (the whole line) and ask for confirmation (see :help :s_flags
)You can omit the c
option if you are sure all replaces are legit.
As kongo2002 says in his answer you could replace the capture groups by \zs
and \ze
:
\zs
will start a match and discard everything before\ze
will end a match and discard everything afterSee :help \ze
and :help \zs
.
Upvotes: 1
Reputation: 1024
If the regex .'.
is accurate enough then you can substitute all occurrences with:
:%s/.\zs'\ze./\\'/g
Instead of using \ze
and \zs
you could use groups (...)
as well. However I find this version slightly more readable.
See :h /\zs
and :h /\ze
for further information.
Upvotes: 4