如何测试一个字符串是否包含多个子字符串之一?

How to test if a string contains one of multiple substrings?

我想知道一个字符串是否包含 abcdefxyz 等之一。我可以这样做:

$a.Contains("abc") -or $a.Contains("def") -or $a.Contains("xyz")

很好,但是如果这个子字符串列表发生变化,我必须更改代码,而且性能很差,因为 $a 被扫描了多次。

有没有一种更有效的方法,只需一次函数调用就可以做到这一点?

正则表达式:$a -match /\a|def|xyz|abc/g (https://regex101.com/r/xV6aS5/1)

  • 匹配原始字符串中任意位置的精确字符: 'Ziggy stardust'-匹配'iggy'

来源:http://ss64.com/ps/syntax-regex.html

您可以使用 -match 方法并使用 string.join 自动创建正则表达式:

$referenz = @('abc', 'def', 'xyz')    
$referenzRegex = [string]::Join('|', $referenz) # create the regex

用法:

"any string containing abc" -match $referenzRegex # true
"any non matching string" -match $referenzRegex #false