21

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
  • 2
    You can not use matchstr like this, 2nd arg of matchstr is a regex pattern, eg: matchstr('ab', '.') will return 'a'.
    – dedowsdi
    Commented Apr 19, 2019 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. Commented Apr 19, 2019 at 5:04

2 Answers 2

24

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
  • 2
    If you want to accept a match anywhere in the string, including the start of the string, then use if stridx(a, b) >= 0 Commented Dec 27, 2020 at 4:32
6

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. Commented May 21, 2021 at 2:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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