9

There is a search and replace operation I am trying to do using backreferencing and regular expressions in vim. Interestingly, it will only recognize the pattern if I do a pure search, but if I do a search and replace it gives me an E486: pattern not found error.

I have a bunch of function calls of the form:

function( Nullable< double >(1.1), map[FOO] );

Where FOO is some different variable name on each line. I want to turn it into

function( othermap[ FOO ], map[FOO] );

If I try

:%s/Null.*\(map[\)\(.*\)\]/othermap[ \2 \], \1\2\]/g

It gives me the "Pattern not found error." Even

:%s/Null.*\(map[\)\(.*\)\]//g 

will not work because it's just not recognizing the pattern. But if I try the following command with the exact same search regex:

/Null.*\(map[\)\(.*\)\]

It highlights correctly. Following which, I can do %s//othermap[ \2 ], \1\2] to do my replacement. So I was able to do my replacement after all, but I can't for the life of me understand why the pattern would be recognized in one case and not in the other.

bhh1988
  • 1,262
  • 3
  • 15
  • 30
  • Possible duplicate of [vim does not find and replace simple phrase that is clearly present](https://stackoverflow.com/questions/5289262/vim-does-not-find-and-replace-simple-phrase-that-is-clearly-present) – Victor Sergienko Mar 04 '18 at 03:56

1 Answers1

11

I can reproduce the result using copy'n'paste from your question to my vim session. The detailed message I get, though, is:

E486: Pattern not found: Null.*\(map[\)\(.*\)\]/othermap[ \2 \], \1\2\]/g

Note that it has lost the s/ at the start.

However, looking rather carefully at this, the trouble is an unescaped [:

s/Null.*\(map[\)\(.*\)\]/othermap[ \2 \], \1\2\]/g
             ^
             |-- here; you need \[ to match the literal

I don't use the % notation; I would automatically write:

:g/Null.*\(map\[\(.*\)\]\)/s//othermap[\2], \1/g

This has slightly different capturing. There was also no need to use the backslash in \] in the replacement string.

However, this command also works for me:

:%s/Null.*\(map\[\(.*\)\]\)/othermap[\2], \1/g
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    oh i didn't know that you had to escape the first square bracket as well. The behavior of the square brackets is strange to me since it often seems to work in many situations even when I don't escape it. Thanks! – bhh1988 Sep 03 '11 at 06:59