简体   繁体   中英

Vim regex not matching spaces in a character class

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?

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\\|[...]\\) .

Vim interprets characters inside of the [ ... ] character classes differently. It's not literally, since that regex wouldn't fully match lambda {sss or lambda {\\\\\\ . What \\s and \\S are interpreted as...I still can't explain.

However, I was able to achieve nearly what I wanted with:

%s/lambda\s*{\([\n a-zA-z]\)*//gc

That ignores punctuation, which I wanted. This works, but is dangerous:

%s/lambda\s*{\([\n a-zA-z]\|.\)*//gc

Because adding on a character after the last character like } causes vim to hang while globbing. So my solution was to add the punctuation I needed into the character class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM