Search code examples
vimbackreferenceregex-lookarounds

Why is my vim zero width positive lookbehind storing a backreference?


I am using Vim, and I have the following code:

print "Number 1 = $no1\n";
print "Number 2 = $no2\n";

When I apply the following substitute command

$s/.*\(\d\\n\)\@<=\(";\)/\1

the result is

1\n
2\n

and when I substitute with backreference \2 instead

$s/.*\(\d\\n\)\@<=\(";\)/\2

the result is

";
";

I thought that I only have one backreference in the regex (the ";) What was stored in \1 appears to be the regex I used within my zero-width positive lookbehind, which I thought would NOT be stored in a backreference.

Am I mistaken?


Solution

  • I think \( is always a capturing back reference. From what I can see from a few attempts, what you want is a \%(, which is a non-capturing back reference.

    So basically, rewriting your substitute as:

    $s/.*\%(\d\\n\)\@<=\(";\)/\1
    

    will put

    ";
    

    to backreference \1, rather than \2