我需要使用PowerShell阅读大量文件,并让所有的电子邮件地址查找文件中的所有邮件地址。我试过这个解决方案使用正则表达式
$myString -match '\[email protected]\w+\.\w+'
问题是变量$matches
只包含第一个匹配项。 我错过了什么吗?
我需要使用PowerShell阅读大量文件,并让所有的电子邮件地址查找文件中的所有邮件地址。我试过这个解决方案使用正则表达式
$myString -match '\[email protected]\w+\.\w+'
问题是变量$matches
只包含第一个匹配项。 我错过了什么吗?
-match
返回的字符串与内容,所以它有一个字符串数组哪里能找到每行的匹配效果更好。你想要的是一个“全球”搜索,我相信它被称为。在PowerShell中,你可以做,使用Select-String
与-AllMatches
参数。
尝试以下操作:
(Select-String -InputObject $myString -Pattern '\[email protected]\w+\.\w+' -AllMatches).Matches
例子:
$myString = @"
[email protected] hhaksda [email protected]
dsajklg [email protected]
"@
PS > (Select-String -InputObject $myString -Pattern '\[email protected]\w+\.\w+' -AllMatches).Matches | ft * -AutoSize
Groups Success Captures Index Length Value
------ ------- -------- ----- ------ -----
{[email protected]} True {[email protected]} 0 14 [email protected]
{[email protected]} True {[email protected]} 23 15 [email protected]
{[email protected]} True {[email protected]} 48 15 [email protected]
的选择字符串的方法效果很好这里。然而,这正则表达式是根本不适合,你应该检查以下类似的问题:Using Regex in Powershell to grab email
你有你有没有注意到一个问题 - 你的正则表达式将错过有效的电子邮件地址,并可能匹配无效的。这不是一个简单的正则表达式匹配有效的电子邮件地址 - 这是在这里出现的SO [相当](https://www.google.com/search?q=regex+to+match+email+address+site话题:stackoverflow.com)[经常](http://stackoverflow.com/search?q=regex+match+email+address) – alroc 2013-03-20 12:40:58
@alroc感谢您的观察。事实上,我正在使用不同的正则表达式来查找电子邮件地址。这只是一个例子,只是为了解这个问题 – Naigel 2013-03-20 12:51:42