检查字符串是否包含数组Powershell中的任何子字符串

tjd*_*bts 18 powershell

我正在研究powershell.我想知道如何检查字符串是否包含数组中的任何子字符串Powershell.i知道如何在python中执行相同的操作.代码如下

  any(substring in string for substring in substring_list)
Run Code Online (Sandbox Code Playgroud)

PowerShell中是否有类似的代码?

我的powershell代码如下.

$a = @('one', 'two', 'three')
$s = "one is first"
Run Code Online (Sandbox Code Playgroud)

我想用$ a验证$ s.如果$ s中的任何字符串都存在于$ s中,则返回True.Is它有可能在PowerShell中

Mic*_*ens 22

为简单起见,使用问题中的实际变量:

$a = @('one', 'two', 'three')
$s = "one is first"
$null -ne ($a | ? { $s -match $_ })  # Returns $true
Run Code Online (Sandbox Code Playgroud)

将$ s修改为包含$ a中的任何内容:

$s = "something else entirely"
$null -ne ($a | ? { $s -match $_ })  # Returns $false
Run Code Online (Sandbox Code Playgroud)

(这比chingNotCHing的答案少了25%,当然使用相同的变量名称:-)

  • 我喜欢这个答案,它简短、甜蜜、有效。我认为只需要一些解释就可以理解正在发生的事情。看了 chingNotCHing 的回答后,我明白了一点。 (4认同)

chi*_*ing 10

($substring_list | %{$string.contains($_)}) -contains $true
Run Code Online (Sandbox Code Playgroud)

应该严格遵循你的单线


eli*_*z82 8

我很惊讶六年来没有人给出这个更简单易读的答案

$a = @("one","two","three")
$s = "one1 is first"

($s -match ($a -join '|')) #return True
Run Code Online (Sandbox Code Playgroud)

因此,只需使用竖线“|”将数组内爆为字符串即可 ,因为这是正则表达式中的交替(“OR”运算符)。 https://www.regular-expressions.info/alternation.html https://blog.robertelder.org/regular-expression-alternation/

另请记住,接受的答案不会搜索完全匹配。如果您想要精确匹配,可以使用 \b (单词边界) https://www.regular-expressions.info/wordboundaries.html

$a = @("one","two","three")
$s = "one1 is first"

($s -match '\b('+($a -join '|')+')\b') #return False
Run Code Online (Sandbox Code Playgroud)


小智 6

Michael Sorens 的代码答案最能避免部分子字符串匹配的陷阱。它只需要轻微的正则表达式修改。如果您有 string $s = "oner is first",则代码仍会返回 true,因为 'one' 将匹配 'oner'(PowerShell 中的匹配意味着第二个字符串包含第一个字符串。

$a = @('one', 'two', 'three')
$s = "oner is first"
$null -ne ($a | ? { $s -match $_ })  # Returns $true
Run Code Online (Sandbox Code Playgroud)

为单词边界 '\b' 添加一些正则表达式,'oner' 上的 r 现在将返回 false:

$null -ne ($a | ? { $s -match "\b$($_)\b" })  # Returns $false
Run Code Online (Sandbox Code Playgroud)


小智 6

对于 PowerShell 版本。5.0+

代替,

$null -ne ($a | ? { $s -match $_ })
Run Code Online (Sandbox Code Playgroud)

试试这个更简单的版本:

$q = "Sun"
$p = "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
[bool]($p -match $q)
Run Code Online (Sandbox Code Playgroud)

$True如果 substring$q在 string 数组中,则返回$p

另一个例子:

if ($p -match $q) {
    Write-Host "Match on Sun !"
}
Run Code Online (Sandbox Code Playgroud)

  • 这是倒退的。问题是关于“$q”而不是“$p”的子字符串。 (5认同)
  • 维姆斯是对的。问题是如何在字符串中搜索数组的元素。这个答案展示了如何在数组元素中搜索字符串。事实恰恰相反。投了反对票。 (3认同)

Loï*_*HEL 1

One way to do this:

$array = @("test", "one")
$str = "oneortwo"
$array|foreach {
    if ($str -match $_) {
        echo "$_ is a substring of $str"
    }
}
Run Code Online (Sandbox Code Playgroud)