puk
puk

Reputation: 16802

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.

Upvotes: 28

Views: 18443

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270775

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

Upvotes: 55

icyrock.com
icyrock.com

Reputation: 28628

From the docs:

  • http://vimdoc.sourceforge.net/htmldoc/usr_41.html

    For strings there are two more items:

    a =~ b      matches with
    a !~ b      does not match with
    

    The left item "a" is used as a string. The right item "b" is used as a pattern, like what's used for searching. Example:

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

Upvotes: 7

Related Questions