PowerShell和-contains运算符 [英] PowerShell and the -contains operator

查看:171
本文介绍了PowerShell和-contains运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

"12-18" -Contains "-"

您会认为此计算结果为true,但并非如此.它将取值为false.我不确定为什么会发生这种情况,但是确实如此.

You’d think this evaluates to true, but it doesn't. This will evaluate to false instead. I’m not sure why this happens, but it does.

为避免这种情况,您可以改用以下方法:

To avoid this, you can use this instead:

"12-18".Contains("-")

现在该表达式的计算结果为true.

Now the expression will evaluate to true.

为什么第一个代码段的行为如此? -有什么与-Contains搭配不好的特殊之处吗? 文档没有提及任何内容.

Why does the first code snippet behave like that? is there something special about - that doesn't play nicely with -Contains? The documentation doesn't mention anything about it.

推荐答案

-Contains运算符不进行子字符串比较,并且匹配项必须在完整的字符串上并用于搜索集合.

The -Contains operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.

从您链接到的文档中:

-包含 说明:遏制运算符. 告诉参考值集合是否包含单个测试值.

-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.

在您提供的示例中,您正在使用仅包含一个字符串项的集合.

In the example you provided you're working with a collection containing just one string item.

如果您阅读链接到的文档,您将看到一个演示此行为的示例:

If you read the documentation you linked to you'll see an example that demonstrates this behaviour:

示例:

PS C:\> "abc", "def" -Contains "def"
True

PS C:\> "Windows", "PowerShell" -Contains "Shell"
False  #Not an exact match

我认为您想要的是 -Match 运算符:

I think what you want is the -Match operator:

"12-18" -Match "-"

哪个返回True.

重要:如注释和正则表达式以执行文本匹配.

Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match operator uses regular expressions to perform text matching.

这篇关于PowerShell和-contains运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆