2016-11-11 63 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} 
相关问题