14

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.

2
  • 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. Apr 19 '19 at 5:04
14

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().

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

There's an even easier way in at least version 8.x which I've been using for some time:

if hostname() =~ '10.12.12.132'

which is a simple regex match expression with ignorecase. Here's the section from the Vim manual that explains comparisons, which includes this operator.

expr5 {cmp} expr5

Compare two expr5 expressions, resulting in a 0 if it evaluates to false, or 1
if it evaluates to true.

                 use 'ignorecase'    match case    ignore case ~
regexp matches           =~             =~#             =~?
regexp doesn't match    !~              !~#             !~?

And as pointed out by Big McLargeHuge in the comment, the specific form in this case is

<string-to-test> =~ <regex-pattern>
1
  • 1
    To clarify, the pattern goes on the RHS. So if you want to test if string a is part of string b, you'd use b =~ a. May 21 at 2:47

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.