=~ 在 VimScript 中是什么意思?

问题描述 投票:0回答:2

我一生都无法在谷歌、这里或帮助文件中找到这个问题的答案。

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

起初我以为

=~
的意思是结尾,但观察这些结果:

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

如果有解释就太好了。尝试破译 VimScript 的网站的链接会更好。

operators vim
2个回答
54
投票

来自 Vim 的在线帮助 (

:h =~
):

比较两个[...]表达式[...]

regexp matches         =~
regexp doesn't match   !~

“=~”和“!~”运算符将左侧参数与右侧参数进行匹配,后者用作模式。请参阅pattern了解什么是模式。 [...]

示例:

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

您可以再次尝试您的测试用例。例如,我得到的与你的不一致:

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

双引号与单引号似乎会影响反斜杠的解释方式:

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

6
投票

来自文档:

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

    对于字符串还有两项:

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

    左边的项“a”用作字符串。正确的项目“b”用作a 模式,就像用于搜索的模式一样。示例:

    :if str =~ " "
    :  echo "str contains a space"
    :endif
    :if str !~ '\.$'
    :  echo "str does not end in a full stop"
    :endif
    
© www.soinside.com 2019 - 2024. All rights reserved.