【问题标题】:Regex to match URL in Powershell正则表达式以匹配 Powershell 中的 URL
【发布时间】:2021-08-12 18:47:19
【问题描述】:

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

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

网址是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   

感谢您的帮助

【问题讨论】:

  • 你期望什么输出?
  • 您的正则表达式中有多个匹配组(..)。它只是返回所有匹配项。按照要求。当前的答案似乎至少在 PowerShell 3.0 上解决了这个问题

标签: regex powershell


【解决方案1】:

试试这个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

祝你好运!享受吧!

【讨论】:

    【解决方案2】:

    用于检查 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

    【讨论】:

    猜你喜欢
    • 2011-08-18
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    相关资源
    最近更新 更多