Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim regex not matching spaces in a character class

Tags:

regex

vim

I'm using vim to do a search and replace with this command:

%s/lambda\s*{\([\n\s\S]\)*//gc

I'm trying to match for all word, endline and whitespace characters after a {. For instance, the entirety of this line should match:

    lambda {
  FactoryGirl.create ...

Instead, it only matches up to the newline and no spaces before FactoryGirl. I've tried manually replacing all the spaces before, just in case there were tab characters instead, but no dice. Can anyone explain why this doesn't work?

like image 617
Eric Hu Avatar asked Sep 04 '12 20:09

Eric Hu


1 Answers

The \s is an atom for whitespace; \n, though it looks similar, syntactically is an escape sequence for a newline character. Inside the collection atom [...], you cannot include other atoms, only characters (including some special ones like \n. From :help /[]:

  • The following translations are accepted when the 'l' flag is not included in 'cpoptions' {not in Vi}:
\e  <Esc>
\t  <Tab>
\r  <CR>    (NOT end-of-line!)
\b  <BS>
\n  line break, see above |/[\n]|
\d123   decimal number of character
\o40    octal number of character up to 0377
\x20    hexadecimal number of character up to 0xff
\u20AC  hex. number of multibyte character up to 0xffff
\U1234  hex. number of multibyte character up to 0xffffffff

NOTE: The other backslash codes mentioned above do not work inside []!

So, either specify the whitespace characters literally [ \t\n...], use the corresponding character class expression [[:space:]...], or combine the atom with the collection via logical or \%(\s\|[...]\).

like image 96
Ingo Karkat Avatar answered Oct 14 '22 10:10

Ingo Karkat