gpt4 book ai didi

PowerShell 和 -contains 运算符

转载 作者:行者123 更新时间:2023-12-03 04:37:16 24 4
gpt4 key购买 nike

考虑以下代码片段:

"12-18" -Contains "-"

您可能认为其计算结果为true,但事实并非如此。这将改为 false。我不确定为什么会发生这种情况,但确实如此。

为了避免这种情况,您可以使用它:

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

现在表达式的计算结果将为 true。

为什么第一个代码片段会有这样的行为? - 有什么特殊之处与 -Contains 不能很好地配合吗? The documentation没有提及任何相关内容。

最佳答案

-Contains 运算符不进行子字符串比较,匹配必须位于完整字符串上,用于搜索集合。

从您链接到的文档:

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

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

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

示例:

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

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

我想你想要的是 -Match运算符:

"12-18" -Match "-"

返回True

重要提示:正如评论和 linked documentation 中所指出的那样,需要注意的是-Match运算符使用regular expressions执行文本匹配。

关于PowerShell 和 -contains 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18877580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com