how to non-capturing search and replace in vim

"Non-capturing" doesn't mean what you think it means. The only difference between \(...\) and \%(...\) is whether or not the subexpression is saved to \1, \2... It will still include the matched content in the match.

You wanted \@<= (:help \@<=):

:s/\(^a*\)\@<=&/\& \&/g

I want to replace the first occurrence of & with & &, and keep everything else as is

Use a substitution command:

:s/&/& &/

Another tip: Vim by default treats ( as a literal character, rather than the start of a group.

Use very magic mode if you want your regex to act more like traditional (Perl) regex.

An easy way to specify very magic mode is to start your regex with \v:

" this is a no-op
:s/\v(this is grouped)/\1/

EDIT: this answer works, but please see @heijp06's very relevant comment below (I wasn't aware that the & character had a special meaning).

Comment pasted here:

It is actually somewhat nontrivial why this answer is correct. An & in the replacement part of a substitution means that what was matched by the pattern in this case that was an & so the end effect is correct.

Tags:

Vim

Regex