Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring in vim script

Is there any substr() like function to get substring in vim script? If not what is the best replacement or alternative for this kind of task?

like image 963
Arafat Hasan Avatar asked Jun 09 '18 16:06

Arafat Hasan


2 Answers

The VimL expression mystring[a:b] returns a substring from byte index a up to (and including) b.

But be aware that the semantics are different from Python's subscript notation or Javascript's str.slice(). In particular, VimL counts the bytes instead of the characters for indexing, and the byte at the end of the range (the byte at index b) is included.

These examples illustrate how the behavior differs:

              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       äö

Also, look up the documentation at :help subscript and :help expr-[:].

like image 61
Arminius Avatar answered Sep 22 '22 12:09

Arminius


it works like python:

echo '0123456'[2:4]
234

For detailed doc:

:h expr-[:]
like image 25
Kent Avatar answered Sep 19 '22 12:09

Kent