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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31132936/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:24:15  来源:igfitidea点击:

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

stringpowershellcompare

提问by vik santata

I wish to know if a string contains one of abc, def, xyz, etc. I could do it like:

我想知道,如果一个字符串包含的一个abcdefxyz等我能做到这一点,如:

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

Well it works, but I have to change code if this substring list changes, and the performance is poor because $ais scanned multiple times.

好吧,它有效,但是如果此子字符串列表更改,我必须更改代码,并且由于$a多次扫描,性能很差。

Is there a more efficient way to do this with just one function call?

有没有更有效的方法来只用一个函数调用来做到这一点?

回答by Martin Brandl

You could use the -match method and create the regex automatically using string.join:

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

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

Usage:

用法:

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

回答by d0n

Regex it: $a -match /\a|def|xyz|abc/g(https://regex101.com/r/xV6aS5/1)

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

  • Match exact characters anywhere in the original string: 'Ziggy stardust' -match 'iggy'
  • 匹配原始字符串中任意位置的精确字符:'Ziggy stardust' -match 'iggy'

source: http://ss64.com/ps/syntax-regex.html

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