vim 正则表达式 - 匹配行尾任意数量的空格,除了 2

vim regex - match any number of whitespace at end of line except 2

我想为 ale 写一个修复程序来删除行尾的所有白色 space 除了双白色 space - 在 markdown 中这用于创建换行符。

我需要匹配“在行尾,1 个或多个白色 space 而不是 2 个白色 space”

有点像 \s\+$\&\s\{^2}$ 除了 ^ 不是大括号内的否定。一些谷歌搜索显示否定元字符的计数似乎是一个特别小众的问题。

(这真的应该是评论,但格式很重要,在这里)

您希望以下代码段在“修复”后如何显示(标有 _ 的空格)?

First line, without trailing spaces
Second line, with one trailing space_
Third line, with two trailing spaces__
Fourth line, with more than two trailing spaces______

您可以使用

:%s/\v(\s)@<!\s(\s{2,})?$//g

详情

  • % - 搜索所有行
  • s - 替换
  • \v - 非常神奇的模式
  • (\s)@<! - 位置前面没有紧跟空格
  • \s - 一个空格
  • (\s{2,})? - 两个或多个空格的可选出现
  • $ - 行尾
  • g - 线上所有出现的地方。

这是 how this regex works(翻译成 PCRE)。