Use lookarounds
I think the simplest :substitute
command might be to use lookarounds:
:%s/<\@<!<<\@!/"/g
This replaces every <
character that is neither preceded nor followed by another <
character.
How it works
It uses a :substitute
command (See :help :substitute
) to replace strings that match the regular expression <\@<!<<\@!
with "
characters.
The regular expression is reasonably simple when broken down. It consists of three parts:
:%s/<\@<!<<\@!/"/g
^
1
In the middle is a single <
character. This is what we want to match.
:%s/<\@<!<<\@!/"/g
^^^^^
2
Before that is: <\@<!
. This is a second <
character followed by Vim's atom for negative lookbehind: \@<!
, which means that our central <
will only be matched if we didn't match a <
here.
:%s/<\@<!<<\@!/"/g
^^^^
3
At the end we have: <\@!
. This is a third <
, this time followed by Vim's atom for negative lookahead: \@!
:our <
will only be matched if it is not followed by a <
.
See :help \@!
and :help \@<!
for more details of Vim's negative lookaround atoms.
%s/\(^\|[^<]\)<\($\|[^<]\)/\1"\2/g
\v
to cut down on the pattern noise though.