2013-03-20 66 views
1

我需要使用PowerShell阅读大量文件,并让所有的电子邮件地址查找文件中的所有邮件地址。我试过这个解决方案使用正则表达式

$myString -match '\[email protected]\w+\.\w+' 

问题是变量$matches只包含第一个匹配项。 我错过了什么吗?

+0

你有你有没有注意到一个问题 - 你的正则表达式将错过有效的电子邮件地址,并可能匹配无​​效的。这不是一个简单的正则表达式匹配有效的电子邮件地址 - 这是在这里出现的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

+0

@alroc感谢您的观察。事实上,我正在使用不同的正则表达式来查找电子邮件地址。这只是一个例子,只是为了解这个问题 – Naigel 2013-03-20 12:51:42

回答

2

-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]