【问题标题】:Issue using [Regex]::Match in powershell在 powershell 中使用 [Regex]::Match 的问题
【发布时间】:2016-08-04 21:47:41
【问题描述】:

我正在尝试从 PowerShell 中的邮件正文中提取 URL。

我正在使用以下正则表达式:(在 this site 上找到)

$regexURL = "@^(https?|ftp)://[^\s/$.?#].[^\s]*$@iS"

然后我循环进入一个邮件文件夹和每个邮件项:

foreach ($Mail in $subfolder.items)  {    
    $a = [Regex]::Match($Mail.Subject, $regexURL).Groups[1].Value
    $b = [Regex]::Match($Mail.Body, $regexURL).Groups[1].Value
}

但即使 Mail.Subject 或 Body 包含有效的 URL,$a 和 $b 仍为空。

恐怕我不明白 Match() 是如何工作的。

感谢您对该问题的任何帮助。 杰罗姆

【问题讨论】:

  • 缩进!请在发布前修复它!
  • 请发布$Mail.Subject 的示例以及您对$a 的期望。
  • @ 有什么用?似乎是另一种语言的正则表达式。试试$regexURL = '(https?|ftp)://[^\s/$.?#].[^\s]*$'iS 在 PS/.NET AFAIK 中不需要修饰符。
  • 例如,$Mail.Subject 可以是“stockoverflow.com”。 $Mail.Body 与最后的空行相同。 '(https?|ftp)://[^\s/$.?#].[^\s]*$' 根本不起作用。暂时只有 "(http[s]?|[s]?ftp[s]?)(:\/\/)([^\s,]+)" 有点(!)工作并给出“http”返回。

标签: regex string powershell match


【解决方案1】:

正则表达式适用于另一种语言(可能是 PHP),因此您需要将其修改为 .NET 语法。 Powershell 默认情况下不区分大小写,S 我认为是 PHP 的优化修饰符,所以我们将跳过这两个。试试:

$regexURL = '(https?|ftp)://[^\s/$.?#].[^\s]*$'

示例:

$regexURL = '(https?|ftp)://[^\s/$.?#].[^\s]*$'

#URL
[regex]::Match("test http://stackoverflow.com/questions/36604481/issue-using-regexmatch-in-powershell/36605171?noredirect=1#comment60807898_36605171", $regexURL).Groups[0].Value
http://stackoverflow.com/questions/36604481/issue-using-regexmatch-in-powershell/36605171?noredirect=1#comment60807898_36605171

#Protocol
[regex]::Match("test http://stackoverflow.com/questions/36604481/issue-using-regexmatch-in-powershell/36605171?noredirect=1#comment60807898_36605171", $regexURL).Groups[1].Value
http

【讨论】:

  • 是的,.NET 不使用修饰符,所以@^ 基本上等同于(?!)
  • 我认为您找到了重点,但仍然无法正常工作。我现在尝试使用: "(http[s]?|[s]?ftp[s]?)(:\/\/)([^\s,]+)" 并在 $b 中返回 "http" .我仍然需要为 PowerShell 5 找到正确的 regexUrl。
  • 它做的正是它应该做的。您在捕获组() 中有http(协议)。比赛本身在第 0 组。请参阅更新答案中的示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-21
  • 2020-11-20
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
相关资源
最近更新 更多