我正在研究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%,当然使用相同的变量名称:-)
chi*_*ing 10
($substring_list | %{$string.contains($_)}) -contains $true
Run Code Online (Sandbox Code Playgroud)
应该严格遵循你的单线
我很惊讶六年来没有人给出这个更简单易读的答案
$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
代替,
$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)
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)
| 归档时间: |
|
| 查看次数: |
38905 次 |
| 最近记录: |