简体   繁体   English

Vim正则表达式不匹配字符类中的空格

[英]Vim regex not matching spaces in a character class

I'm using vim to do a search and replace with this command: 我正在使用vim进行搜索并替换为此命令:

%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 . 相反,它只匹配换行符,并且在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; \\s是空白的原子; \\n , though it looks similar, syntactically is an escape sequence for a newline character. \\n ,尽管它看起来很相似,但语法上是换行符的转义序列。 Inside the collection atom [...] , you cannot include other atoms, only characters (including some special ones like \\n . From :help /[] : 在集合原子[...] ,你不能包含其他原子,只能包含一些特殊字符(包括\\n 。来自:help /[]

  • The following translations are accepted when the 'l' flag is not included in 'cpoptions' {not in Vi}: 当'l'标志未包含在'cpoptions'{Vi 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\\|[...]\\) . 因此,要么按字面指定空格字符[ \\t\\n...] ,请使用相应的字符类表达式[[:space:]...] ,或者通过逻辑或\\%(\\s\\|[...]\\)将原子与集合组合在一起\\%(\\s\\|[...]\\)

Vim interprets characters inside of the [ ... ] character classes differently. Vim以不同的方式解释[ ... ]字符类中的字符。 It's not literally, since that regex wouldn't fully match lambda {sss or lambda {\\\\\\ . 这不是字面意思,因为正则表达式不能完全匹配lambda {ssslambda {\\\\\\ What \\s and \\S are interpreted as...I still can't explain. 什么\\s\\S被解释为......我仍然无法解释。

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. 由于最后一个字符等之后加入一个字符}会使Vim挂起,而通配符。 So my solution was to add the punctuation I needed into the character class. 所以我的解决方案是在字符类中添加我需要的标点符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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