【问题标题】:Remove leading and trailing whitespaces from string in Vim从 Vim 中的字符串中删除前导和尾随空格
【发布时间】:2022-01-24 05:08:20
【问题描述】:

我需要一个从字符串中去除前导和尾随空格的函数。

func! RemoveWhitespaces(String)
    ...
    return formattedString
endfunc

我只能找到将缓冲区中的行替换为去掉空格的方法,但这不是我想要的。

我应该如何完成这个功能?

【问题讨论】:

标签: vim neovim removing-whitespace


【解决方案1】:

我的尝试:

func! RemoveWhitespaces(string)
    let string = a:string
    let result = substitute(string, '\s\+$', '', '')
    let result = substitute(string, '^\s\+', '', '')
    silent return result
endfunc

现在要获得结果,您可以:

:let var=RemoveWhitespaces('  my string with spaces   ')
:echo var

更新:

正如romainl 所评论的,有一个更简单的方法:

:let var=trim('   some text   ')

【讨论】:

  • :help trim()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 2011-10-02
相关资源
最近更新 更多