在PowerShell中检查字符串是否包含数组中的任何子字符串 [英] Check if a string contains any substring in an array in PowerShell

查看:79
本文介绍了在PowerShell中检查字符串是否包含数组中的任何子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 PowerShell.我想知道如何在 PowerShell 中检查字符串是否包含数组中的任何子字符串.我知道如何在 Python 中做同样的事情.代码如下:

any(substring in string for substring_list 中的子串)

PowerShell 中是否有类似的代码可用?

我的 PowerShell 代码如下.

$a = @('one', 'two', 'three')$s = "一个是第一个";

我想用 $a 验证 $s.如果 $a 中的任何字符串存在于 $s 中,则返回 True.是否可以在 PowerShell 中使用?

解决方案

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

$a = @('one', 'two', 'three')$s = "一个是第一个";$null -ne ($a | ? { $s -match $_ }) # 返回 $true

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

$s = 完全是别的东西";$null -ne ($a | ? { $s -match $_ }) # 返回 $false

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

I am studying PowerShell. I want to know how to check if a string contains any substring in an array in PowerShell. I know how to do the same in Python. The code is given below:

any(substring in string for substring in substring_list)

Is there similar code available in PowerShell?

My PowerShell code is given below.

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

I want to validate $s with $a. If any string in $a is present in $s then return True. Is it possible in PowerShell?

解决方案

Using the actual variables in the question for simplicity:

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

Modifying $s to not include anything in $a:

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

(That's about 25% fewer characters than chingNotCHing's answer, using the same variable names of course :-)

这篇关于在PowerShell中检查字符串是否包含数组中的任何子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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