问题
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