我在这里找到了多个示例,但是由于某些原因,它无法正常工作。
我有一个正则表达式列表,正在检查一个值,但似乎找不到匹配项。
我正在尝试匹配域。例如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}
}
}
在此先感谢您的帮助。
答案 0 :(得分:1)
当前代码的问题是将正则表达式放在-match
运算符的左侧。 [ grin ]交换了该内容,您的代码otta正常运行。
考虑到LotPings指出的关于区分大小写的内容,并使用正则表达式或符号对每个URL进行一个测试,下面是其中的一个演示。 \b
用于单词边界,|
是正则表达式或符号。 $RegexURL_WhiteList
部分从第一个数组构建该正则表达式模式。如果我不清楚,请询问...
$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.