使用Where对象将某物与数组列表匹配



我在这里找到了很多尝试的例子,但由于某种原因,它不起作用。

我有一个正则表达式列表,我正在对照一个值进行检查,但似乎找不到匹配项。

我正在尝试匹配域。例如gmail.com、yahoo.com、live.com等

我正在导入一个csv来获取域,并调试了此代码以确保值符合我的期望。例如"gmail.com">

正则表达式示例AKA$FinalWhiteListArray

(?i)gmail.com
(?i)yahoo.com
(?i)live.com

代码

Function CheckDirectoryForCSVFilesToSearch {
$global:CSVFiles = Get-ChildItem $Global:Directory -recurse -Include *.csv | % {$_.FullName} #removed -recurse
}
Function ImportCSVReports {
Foreach ($CurrentChangeReport in $global:CSVFiles) {
$global:ImportedChangeReport = Import-csv $CurrentChangeReport
}
}
Function CreateWhiteListArrayNOREGEX {
$Global:FinalWhiteListArray = New-Object System.Collections.ArrayList
$WhiteListPath = $Global:ScriptRootDir + "" + "WhiteList.txt"
$Global:FinalWhiteListArray= Get-Content $WhiteListPath
}
$Global:ScriptRootDir = Split-Path -Path $psISE.CurrentFile.FullPath
$Global:Directory = $Global:ScriptRootDir + "" + "Reports to Search" + "" #Where to search for CSV files
CheckDirectoryForCSVFilesToSearch
ImportCSVReports
CreateWhiteListArrayNOREGEX
Foreach ($Global:Change in $global:ImportedChangeReport){
If (-not ([string]::IsNullOrEmpty($Global:Change.Previous_Provider_Contact_Email))){
$pos = $Global:Change.Provider_Contact_Email.IndexOf("@")
$leftPart = $Global:Change.Provider_Contact_Email.Substring(0, $pos)
$Global:Domain = $Global:Change.Provider_Contact_Email.Substring($pos+1)
$results = $Global:FinalWhiteListArray | Where-Object { $_ -match $global:Domain}
}
}

提前感谢您的帮助。

当前代码的问题是将regex放在-match运算符的左侧。[grin]交换它,您的代码就可以运行了。

考虑到LotPings指出的大小写敏感性,并使用regex OR符号对每个URL进行一次测试,下面是其中的一些演示。b表示单词边界,|表示regex OR符号。CCD_ 4部分从第一个数组构建正则表达式模式。如果我没有说清楚,请问。。。

$URL_WhiteList = @(
'gmail.com'
'yahoo.com'
'live.com'
)
$RegexURL_WhiteList = -join @('b' ,(@($URL_WhiteList |
ForEach-Object {
[regex]::Escape($_)
}) -join '|b'))
$NeedFiltering = @(
'example.com/this/that'
'GMail.com'
'gmailstuff.org/NothingElse'
'NotReallyYahoo.com'
'www.yahoo.com'
'SomewhereFarAway.net/maybe/not/yet'
'live.net'
'Live.com/other/another'
)
foreach ($NF_Item in $NeedFiltering)
{
if ($NF_Item -match $RegexURL_WhiteList)
{
'[ {0} ] matched one of the test URLs.' -f $NF_Item 
}
}

输出。。。

[ GMail.com ] matched one of the test URLs.
[ www.yahoo.com ] matched one of the test URLs.
[ Live.com/other/another ] matched one of the test URLs.

最新更新