Question

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?

Was it helpful?

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

OTHER TIPS

When you apply the following substitute command:

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

... the result is:

1\n
2\n

As should be expected, because you've captured the below expression in the \1 capturing group:

\(\d\\n\)

... and when you substitute with backreference \2 instead

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

... the result is:

";
";

As should be expected, because you've captured the below expression in the second capturing group:

\(";\)

I'm unclear what you're trying to do. What output were you expecting from the above substitutions?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top