匹配发件人SMTP地址的正则表达式

时间:2018-01-18 22:22:00

标签: regex powershell email

我在PowerShell中有一个正常的表达式,它可以从Outlook文件(* .msg)中的电子邮件标题中获取所有SMTP地址。

From: <Him him@hotmail.com>
To: Me <me@gmail.com>
CC: Somebody <someone@outlook.com>
Subject: Re: Testing RegEX
Date: Tue, 16 Jan 2018 13:19:15 +0000

获取所有标题的工作代码

$header = Get-Content c:\work\headers.txt
$regex  = ‘\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b’
(Select-String -InputObject $header -Pattern $regex -AllMatches).Matches.Value

使用这个正则表达式,我将获得 him@hotmail.com me@gmail.com someone@outlook.com

但我只需要 him@hotmail.com 发件人:行中的SMTP地址。

有时候,标题中找到了很长的SMTP路由地址,我想排除这些地址。示例 56DC1F3F67BF7844921154175A149C7C0522660A@mymailserver.subdomain.company.com 。 所以我试图排除那些带有正则表达式的,但是当尝试将SMTP地址的最大长度设置为50时:

(\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b){0,50}

它不起作用,所以显然有些语法错误。 你能给我的任何提示吗?

1 个答案:

答案 0 :(得分:1)

如果您只想要From:标题行中的地址,那么您应该只匹配:

$regex = '(?<=^From: .*?)\b[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b'
(Get-Content 'c:\work\headers.txt') -match $regex | ForEach-Object {
    $matches[0]
}

(?<=^From: .*?)是一个积极的lookbehind断言,意味着它在模式匹配中使用,但不包括在返回的结果中。

相关问题