Search code examples
operatorsvim

What does =~ mean in VimScript?


I can't for the life of me find an answer to this either on google or here or in the help files.

if "test.c" =~ "\.c"

At first I thought =~ mean ends in, but observe these results:

Command                               Result
echo "test.c" =~ "\.c"                1
echo "test.c" =~ "\.pc"               0
echo "test.pc" =~ "\.c"               1
echo "testc" =~ "\.c"                 1
echo "ctest" =~ "\.c"                 1
echo "ctestp" =~ "\.pc"               0
echo "pctestp" =~ "\.pc"              0
echo ".pctestp" =~ "\.pc"             0

An explanation would be great. A link to a site attempting to decipher VimScript would be even better.


Solution

  • From Vim's online help (:h =~):

    Compare two [...] expressions [...]

    regexp matches         =~
    regexp doesn't match   !~
    

    The "=~" and "!~" operators match the lefthand argument with the righthand argument, which is used as a pattern. See pattern for what a pattern is. [...]

    Example:

        :if str =~ " "
        :  echo "str contains a space"
        :endif
        :if str !~ '\.$'
        :  echo "str does not end in a full stop"
        :endif
    

    You might try your test cases again. I get, for example, inconsistent with yours:

    echo ".pctestp" =~ "\.pc"             1
    

    And double-quotes vs single quotes seem to affect how the backslash is interpreted:

    echo "test.pc" =~ "\.c"               1
    echo "test.pc" =~ '\.c'               0