I was wondering what is the proper way to test whether a substring is included in some other string. If I want to check if string a is part of string b, I'm currently using

matchstr(b, a) != ""

to check if a is a substring of b. Is there a more "proper" way of doing it, since this seems like a bit of a hack.

  • 1
    You can not use matchstr like this, 2nd arg of matchstr is a regex pattern, eg: matchstr('ab', '.') will return 'a'. – dedowsdi Apr 19 '19 at 5:01
  • @dedowsdi valid comment. This might be relevant to other users, but in my case these strings are guaranteed to not contain regex. – SalmonKiller Apr 19 '19 at 5:04

For this there is the function stridx().

let a = "Vi and Vim"
let b = "and"
echo stridx(a, b)
" echos 3

If the substring is not found stridx() returns -1. The function also supports a third argument to specify the start index to search from.

See :help stridx().

  • If you want to accept a match anywhere in the string, including the start of the string, then use if stridx(a, b) >= 0 – joeytwiddle Dec 27 '20 at 4:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.