vim 脚本中的子字符串

Substring in vim script

在vim脚本中有没有类似substr()的函数获取子字符串?如果不是,这种任务的最佳替代品是什么?

它的工作方式类似于 python:

echo '0123456'[2:4]
234

详细文档:

:h expr-[:]

取决于您想要字节范围还是字符范围。对于 be 的字节范围 str[b:e],但对于字符范围,您需要 byteidx 函数:

str[byteidx(str,b):byteidx(str,e+1)-1]

对于多字节字符,结果不同。

对于多字节字符,还有:h strcharpart()

如果您的旧版本 Vim 中不存在该功能,则可以使用例如

进行模拟
function! lh#encoding#strpart(mb_string, p, l)
  " call lh#assert#value(lh#encoding#strlen(a:mb_string)).is_ge(a:p+a:l)
  return matchstr(a:mb_string, '.\{,'.a:l.'}', 0, a:p+1)
endfunction

VimL 表达式 mystring[a:b] returns 从字节索引 a 到(包括)b.

的子字符串

但请注意 语义不同于 Python 的 subscript notation or Javascript's str.slice()。特别是,VimL 计算索引的字节数而不是字符数,并且包括范围末尾的字节(索引 b 处的字节)。

这些示例说明了行为的不同之处:

              VimL        Python
--------------------------------
s = "abcdef"
s[0]          a           a
s[5]          f           f
s[0:1]        ab          a
s[2:4]        cde         cd
s[-1:]        f           f
s[:-1]        abcdef      abcde
s[-2:-1]      ef          e

s = "äöü"
s[0:2]        ä\xc3       äö

此外,请在 :help subscript:help expr-[:] 中查找文档。