2016-11-11 80 views
0

我有一個文本文件domains.txtPowerShell的比較一個數組作爲另一個數組

$domains = ‘c:\domains.txt’ 
$list = Get-Content $domains 

google.com 
google.js 

和數組的子

$array = @(".php",".zip",".html",".htm",".js",".png",".ico",".0",".jpg") 

在$域中任何的東西在@arr結束不應該在我的最終名單

因此,google.com將在最終名單,但谷歌.js不會。

我發現了一些其他的stackoverflow代碼,給了我正在尋找的確切的相反,但是,我不能得到它逆轉!

這給了我想要的完全相反,我該如何扭轉它?

$domains = ‘c:\domains.txt’ 
$list = Get-Content $domains 

$array = @(".php",".zip",".html",".htm",".js",".png",".ico",".0",".jpg") 

$found = @{} 
$list | % { 
    $line = $_ 
    foreach ($item in $array) { 
     if ($line -match $item) { $found[$line] = $true } 
    } 
} 

$found.Keys | write-host 

這給了我google.js我需要它給我google.com。

我試過了 - 不匹配等,無法讓它扭轉。

在此先感謝和更多的解釋更好!

回答

0

取下. s,將這些項目一起混合爲一個正則表達式OR,在字符串尾部的標記上標記,並根據它過濾域。

$array = @("php","zip","html","htm","js","png","ico","0","jpg") 


       # build a regex of 
       # .(php|zip|html|htm|...)$ 

       # and filter the list with it 
$list -notmatch "\.($($array -join '|'))`$" 

無論如何,反轉結果的簡單方法是步行通過$found.keys | where { $_ -notin $list }。或將您的測試更改爲$line -notmatch $item

但請注意,您正在進行正則表達式匹配,並且top500.org之類的內容會與.0匹配並將結果拋出。如果您需要特別匹配,則需要使用類似$line.EndsWith($item)之類的內容。

+0

神,正則表達式是一個惡夢,你是怎麼掌握的? ^。^ – 4c74356b41

+1

@ 4c74356b41我遠沒有接近它的主人,但知道它是一個狀態機的方式確實有幫助。看看它在這裏做什麼:https://www.debuggex.com/r/MKHbIUS-LTadXlbl 匹配一個點,然後分支試圖匹配任何這些分支,然後一起回來試圖匹配字符串的特殊結尾字符。並在https://regex101.com/r/lxPAUx/3上看到它,右邊是一步一步解釋 - 然後單擊左邊的正則表達式調試器,它會遍歷它正在執行的步驟。 – TessellatingHeckler

+1

@TessellatingHeckler大的回答,甚至更多的鏈接和解釋在您的評論! – jreacher403

0

其他的解決辦法

$array = @(".php",".zip",".html",".htm",".js",".png",".ico",".0",".jpg") 
get-content C:\domains.txt | where {[System.IO.Path]::GetExtension($_) -notin $array} 
相關問題