Ruby的strip()(条带前导和尾随空格)是否有vimscript等价物?

dan*_*dan 20 vim

我正在寻找一个VimScript函数,它可以在字符串之前去除任何尾随或前导空格.

DrA*_*rAl 28

8.0.1630 vim以来trim().

对于旧版本:假设您尝试在vimscript中的变量上执行此操作,您可以执行以下操作:

let new_var = substitute(var, '^\s*\(.\{-}\)\s*$', '\1', '')
Run Code Online (Sandbox Code Playgroud)

如果你愿意,你可以随时让自己的功能:

function! Strip(input_string)
    return substitute(a:input_string, '^\s*\(.\{-}\)\s*$', '\1', '')
endfunction

let new_var = Strip(var)
Run Code Online (Sandbox Code Playgroud)

  • @Zyx:我认为我的变体更快,因为它始终锚定在行的开头,所以解析器不必尝试匹配每个单个字符(这也意味着它不需要'g'标志来让它继续尝试). (2认同)

小智 7

8.0.1630开始, vim具有内置trim()功能来执行此操作。从文档:

trim({text}[, {mask}])

  Return {text} as a String where any character in {mask} is
  removed from the beginning and  end of {text}.
  If {mask} is not given, {mask} is all characters up to 0x20,
  which includes Tab, space, NL and CR, plus the non-breaking
  space character 0xa0.
  This code deals with multibyte characters properly.
Run Code Online (Sandbox Code Playgroud)

因此,调用trim(var)会从中删除开头和结尾的空格var