在 Powershell 中匹配 URL 的正则表达式

Regex to match URL in Powershell

我是编程新手,Powershell,我编写了以下脚本;它解析指定文件夹中的所有电子邮件并从中提取 URLs。该脚本使用正则表达式模式来识别 URL,然后将它们提取到文本文件中。提取的文本然后通过另一个命令 运行 试图删除 http://https:// 部分(我需要帮助来解决这个问题),这些被放入另一个文本文件中,我再次从中删除重复项。

我遇到的主要问题是正则表达式似乎无法正确提取网址。我得到的类似于我在下面创建的示例:

URL 是 http://www.dropbox.com/3jksffpwe/asdj.exe 但我最终得到

dropbox.com/3jksffpwe/asdj.exe
dropbox.com 
drop  
dropbox

剧本是

#Adjust paths to location of saved Emails
$in_files = ‘C:\temp\*.eml, *.msg’  
$out_file = ‘C:\temp\Output.txt’  
$Working_file = ‘C:\temp\working.txt'  
$Parsed_file = ‘C:\temp\cleaned.txt'  

# Removes the old output file from earlier runs.
if (Test-Path $Parsed_file) {
  Remove-Item $Parsed_file
}

# regex to parse thru each email and extract the URLs to a text file
$regex = ‘([a-zA-Z]{3,})://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)*?’  
select-string -Path $in_files -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value } > $out_file

#Parses thru the output of urls to strip out the http or https portion  
Get-Content $Out_file | ForEach-Object {$_.SubString(7)} | Out-File    $Working_file


#Parses thru again to remove exact duplicates  
 $set = @{}  
 Get-Content $Working_file | %{  
   if (!$set.Contains($_)) {  
       $set.Add($_, $null)  
        $_  
    }  
} | Set-Content $Parsed_file  


#Removes the files no longer required  
Del $out_file, $Working_file  

#Confirms if the email messages should be removed  
$Response = Read-Host "Do you want to remove the old messages? (Y|N)"  

If ($Response -eq "Y") {del *.eml, *msg}  

#Opens the output file in notepad  
Notepad $Parsed_file  

Exit   

感谢您的帮助

用于检查 URL 的正则表达式可以像这样:

(?i)\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))

查看更多信息here

试试这个 RegEx:

(http[s]?|[s]?ftp[s]?)(:\/\/)([^\s,]+)

但请记住,powershell -match 仅捕获第一个匹配项。要捕获所有匹配项,您可以这样做:

$txt="https://test.com, http://tes2.net, http:/test.com, http://test3.ro, text, http//:wrong.value";$hash=@{};$txt|select-string -AllMatches '(http[s]?|[s]?ftp[s]?)(:\/\/)([^\s,]+)'|%{$hash."Valid URLs"=$_.Matches.value};$hash

祝你好运!享受吧!