1

I usually do a search and replace in vim that looks like this:

:%s/\([\.!?]\|[\.!?]"\)\s\s/\1text /g

So it looks for either a period, exclamation point, question mark, or any of the above followed by a quote and two spaces. It works fine.

But when I map this in my vimrc like so

map <F4> :%s/\([\.!?]\|[\.!?]"\)\s\s/\1text /g<CR>

and then press F4 I get this error message:

E486: Pattern not found: \([\.!?]|[\.!?]"\)\s\s

It is removing the backslash before the pipe for some reason and I have no idea why. Does anyone know how to correct this behavior?

1 Answer 1

4

In a :mapping, the pipe character is special. Use <Bar> instead:

:noremap <F4> :%s/\([\.!?]\<Bar>[\.!?]"\)\s\s/\1text /g<CR>

Also, you should use :noremap; it makes the mapping immune to remapping and recursion.

3
  • Thanks for the info on recursion too. Helped me clean up the vimrc file.
    – thequerist
    Mar 6, 2013 at 14:40
  • 1
    Lets clean up that regex! The matching group does not need alternation (the \|) instead you can get by with \=. \= matches 0 or 1 times, as many as possible (think Perl's ?). That makes the substitution: %s/\([\.!?]"\=\)\s\s/\1text /g. Because we are not using the pipe symbol the <bar> is not needed. Mar 6, 2013 at 14:46
  • Thanks, the obvious answer always escapes me.
    – thequerist
    Mar 6, 2013 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.