【问题标题】:Powershell string does not containPowershell 字符串不包含
【发布时间】:2015-01-15 18:27:06
【问题描述】:

我有一些接受字符串的代码,

Foreach($user in $allUsers){
    if($user.DisplayName.ToLower().Contains("example.com") -or $user.DisplayName.ToLower()) {
    } else {
        $output3 = $externalUsers.Rows.Add($user.DisplayName)
    }
}

-or 之后的if 的一部分我需要检查字符串是否不包含@ 符号。如何检查@符号是否丢失?

【问题讨论】:

  • .Contains() 返回一个布尔值。只需检查!($user.DisplayName.ToLower().Contains("@"))?
  • 完美!如果您将此创建为答案,我会接受它。

标签: string powershell


【解决方案1】:

有一百万种方法可以做到这一点,由于可读性,我可能会选择以下方法:

$user.DisplayName -inotmatch "@"

-match 运算符使用右侧的模式对左侧操作数进行正则表达式匹配。

使用 i 前缀使其明确区分大小写-insensitive,not 前缀否定表达式

你也可以这样做:

-not($user.DisplayName.ToLower().Contains("@"))
or
!$user.DisplayName.ToLower().Contains("@")

对于简单的通配符文本匹配(也许你讨厌正则表达式,我知道什么?):

$user.DisplayName -notlike "*@*"

或者使用 IndexOf 查找子字符串;

$user.DisplayName.IndexOf("@") -eq (-1)

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 2022-01-22
    • 1970-01-01
    • 2016-05-13
    • 2014-04-17
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多