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

偶尔善良 提交于 2019-12-07 01:33:42

问题


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

$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 $a is scanned multiple times.

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


回答1:


You could use the -match method and create the regex automatically using 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



回答2:


Regex it: $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'

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



来源:https://stackoverflow.com/questions/31132936/how-to-test-if-a-string-contains-one-of-multiple-substrings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!