如何测试一个字符串是否包含多个子字符串之一? [英] How to test if a string contains one of multiple substrings?
本文介绍了如何测试一个字符串是否包含多个子字符串之一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道一个字符串是否包含 abc
, def
, xyz之一
等。我可以这样:
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")
很好,它可以工作,但是如果此子字符串列表发生更改,我必须更改代码,并且性能很差,因为 $ a
被多次扫描了。
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?
推荐答案
您可以使用-match方法并使用string.join自动创建正则表达式:
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
用法:
"any string containing abc" -match $referenzRegex # true
"any non matching string" -match $referenzRegex #false
这篇关于如何测试一个字符串是否包含多个子字符串之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文