2013-03-20 62 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]